window.onscroll = scrollEvent;
function scrollEvent() {
   if ($('screenBorder').style.display != 'none') {
		centerCover();
   }
}

function setBackground(elem, color) {
	elem.style.backgroundColor = color;
}

function clearBackground(elem) {
	elem.style.backgroundColor = '';
}

function getScrollXY(a) {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  if (a=='x') return scrOfX;
  else return scrOfY;
}

function getWinDim(a) {
	var winX = document.documentElement.clientWidth;
	var winY = document.documentElement.clientHeight;
	if (a=='x') return winX;
	else return winY;
}

function initialize() {
/*
	if (getCookie("fontOffset") == null) {
		setCookie("fontOffset",0);
	}
	changeFontSize(Number(getCookie("fontOffset")),true);
*/
	runOnload();
}

function changeFontReset() {
	setCookie("fontOffset",0);
	changeFontSize(0,true,true);
}

function refreshFont() {
	changeFontSize(0);
}

function changeFontSize(inc,u,reset) {
	if (!u) { 
		var newOffset = Number(getCookie("fontOffset"))+Number(inc);
		setCookie("fontOffset",newOffset); 
	}
	var p = document.getElementsByTagName('p');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 12;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h1');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 24;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h2');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 20;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h3');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 16;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h4');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 14;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h5');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 12;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('h6');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 11;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('li');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 12;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('em');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 12;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('select');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 14;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('input');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 14;
		}
		p[n].style.fontSize = size+inc +'px';
	}
	var p = document.getElementsByTagName('textarea');
	for (n=0; n<p.length; n++) {
		if (p[n].style.fontSize && reset != true) {
			var size = parseInt(p[n].style.fontSize.replace("px",""));
		} else {
			var size = 12;
		}
		p[n].style.fontSize = size+inc +'px';
	}
}

function toggleDivS(a) {
  if ($(a).style.display == 'none') $(a).style.display = 'inline';
  else $(a).style.display = 'none';
}

function toggleDiv(a,n) {
	if (a == 'learnMore') {
		if ($('tableOfContents'+n).style.display != 'none') Effect.BlindUp('tableOfContents'+n);
		if ($('authorInfo'+n).style.display != 'none') Effect.BlindUp('authorInfo'+n);
	}
	else if (a == 'tableOfContents') {
		if ($('learnMore'+n).style.display != 'none') Effect.BlindUp('learnMore'+n);
		if ($('authorInfo'+n).style.display != 'none') Effect.BlindUp('authorInfo'+n);
	}
	else if (a == 'authorInfo') {
		if ($('learnMore'+n).style.display != 'none') Effect.BlindUp('learnMore'+n);
		if ($('tableOfContents'+n).style.display != 'none') Effect.BlindUp('tableOfContents'+n);
	}
	
	if ($(a+n).style.display == 'none') Effect.BlindDown(a+n);
	else Effect.BlindUp(a+n);
}

function centerCover(w,h) {
	$('screenCover').style.marginLeft = getScrollXY('x')+'px';
	$('screenCover').style.marginTop = getScrollXY('y')+'px';
	$('screenBorder').style.marginLeft = ((getWinDim('x')-w)/2)+'px';
	$('screenBorder').style.marginTop =  ((getWinDim('y')-h)/2)+getScrollXY('y')+'px';
}

function showCover(w,h) {
 if (w != undefined && h != undefined) {
  w = parseInt(w)+30;
  h = parseInt(h)+30;
  ww = w;
  hh = h-10;
	$('screenBorder').style.width = w+'px';
	$('screenBorder').style.height = h+'px';
	$('screenBorderInside').style.width = ww+'px';
	$('screenBorderInside').style.height = hh+'px';
  $('screenBorder').style.left = '0px';
	$('screenBorder').style.top = '0px';
	$('screenCover').style.width = getWinDim('x')+'px';
	$('screenCover').style.height = getWinDim('y')+'px';
	$('screenCover').style.left = '0px';
	$('screenCover').style.top = '0px';
	centerCover(w,h);
	Effect.Appear('screenBorder',{from:0,to:.85,duration:.5});
	Effect.Appear('screenCover',{from:0,to:.3,duration:.5});
 }
}

function playDemo(pid,title,controller) {
  if (pid == -1) { pid = 308; title="prealgebra"; }
  if (title == undefined) { var title="not specified"; }
  if (controller == undefined) { var controller="not specified"; }
  	var param = "pid="+pid+"&ptype=video";
  	new Ajax.Updater("demoPlayer", "/ajax/multipopup/" , {
		method:'post',
		parameters: param,
		asynchronous:true,
		evalScripts:true,
		onSuccess: function(transport) {
		} 
	});
    pageTracker._trackEvent("popup","video",title+" ("+controller+")");
    pageTracker._trackPageview("/"+controller+"/popup/video/"+title);  	
}

function playLectureID(lectureID,title,controller) {
  if (title == undefined) { var title="not specified"; }
  if (controller == undefined) { var controller="not specified"; }
  var param = "lectureID="+lectureID+"&ptype=video";
  new Ajax.Updater("demoPlayer", "/ajax/popup/" , {
  		method:'post',
  		parameters: param,
  		asynchronous:true,
  		evalScripts:true,
  		onSuccess: function(transport) {
  		} 
  	});
}

function playLectureFromGroup(lectureID,pid,title,controller) {
  if (title == undefined) { var title="not specified"; }
  if (controller == undefined) { var controller="not specified"; }
  var param = "lectureID="+lectureID+"&ptype=video"+"&pid="+pid;
  new Ajax.Updater("demoPlayer", "/ajax/multipopup/" , {
  		method:'post',
  		parameters: param,
  		asynchronous:true,
  		evalScripts:true,
  		onSuccess: function(transport) {
  		} 
  	});
}

function playTestExam() {
  curQ = 1;
  $('popUpBox').innerHTML = "";
  var width=720;
  var height=539;
 	$('popUpBox').style.width = width+'px';
	$('popUpBox').style.height = height+'px';
		new Ajax.Updater("popUpBox", "/ajax/testexam/?reload=true" , {
  		method:'post',
			asynchronous:true,
			evalScripts:true
		});
	$('popUpBox').style.marginLeft = ((getWinDim('x')-width)/2)+'px';
	$('popUpBox').style.marginTop =  ((getWinDim('y')-height)/2)+getScrollXY('y')+'px';
	//Effect.Grow('popUpBox');
	$('popUpBox').style.display = 'block';
	showCover(width,height);
  pageTracker._trackEvent("popup","testexam","algebra");
  pageTracker._trackPageview("/popup/testexam/algebra");
}

function closeDemo() {
	$('demoPlayer').innerHTML = "";
	$('screenBorder').style.display = 'none';
	$('screenCover').style.display = 'none';
}

function showPopup(controller,content,width,height,bgcolor,caption) {
	$('popUpBox').innerHTML = "";
	if (width == undefined) {
		if (content.indexOf('prealgebra') > 0) { var width=760;var height=539; }
		else if (content.indexOf('beginningalgebra') > 0) { var width=744;var height=647; }
		else if (content.indexOf('intermediatealgebra') > 0) { var width=648;var height=437; }
		else if (content.indexOf('collegealgebra') > 0) { var width=648;var height=437; }
		else if (content.indexOf('precalculus') > 0) { var width=660;var height=506; }
		else if (content.indexOf('trigonometry') > 0) { var width=643;var height=682; }
		else if (content.indexOf('calculus') > 0) { var width=760;var height=539; }
		else if (content.indexOf('biology') > 0) { var width=648;var height=450; }
		else if (content.indexOf('chemistry') > 0) { var width=648;var height=450; }
		else if (content.indexOf('physics') > 0) { var width=648;var height=450; }
		else if (content.indexOf('microeconomics') > 0) { var width=648;var height=450; }
		else if (content.indexOf('macroeconomics') > 0) { var width=648;var height=450; }
		else if (content.indexOf('economics') > 0) { var width=648;var height=450; }
		else if (content.indexOf('americangovernment') > 0) { var width=643;var height=413; }
		else if (content.indexOf('publicspeaking') > 0) { var width=643;var height=413; }
		else if (content.indexOf('grade6math') > 0) { var width=760;var height=539; }
		else { width='100%';height='100%'; }
	}
	if (content.indexOf('prealgebra') > 0) { var pname="prealgebra"; }
	else if (content.indexOf('beginningalgebra') > 0) { var pname="beginningalgebra"; }
	else if (content.indexOf('intermediatealgebra') > 0) { var pname="intermediatealgebra"; }
	else if (content.indexOf('collegealgebra') > 0) { var pname="collegealgebra"; }
	else if (content.indexOf('precalculus') > 0) { var pname="precalculus"; }
	else if (content.indexOf('trigonometry') > 0) { var pname="trigonometry"; }
	else if (content.indexOf('calculus') > 0) { var pname="calculus"; }
	else if (content.indexOf('biology') > 0) { var pname="biology"; }
	else if (content.indexOf('chemistry') > 0) { var pname="chemistry"; }
	else if (content.indexOf('physics') > 0) { var pname="physics"; }
	else if (content.indexOf('microeconomics') > 0) { var pname="microeconomics"; }
	else if (content.indexOf('macroeconomics') > 0) { var pname="macroeconomics"; }
	else if (content.indexOf('economics') > 0) { var pname="economics"; }
	else if (content.indexOf('americangovernment') > 0) { var pname="americangovernment"; }
	else if (content.indexOf('publicspeaking') > 0) { var pname="publicspeaking"; }
	else if (content.indexOf('grade6math') > 0) { var pname="grade6math"; }

	if (bgcolor == undefined) { var bgcolor="000000"; }
	$('popUpBox').style.backgroundColor = '#'+bgcolor;
	$('popUpBox').style.width = width+'px';
	$('popUpBox').style.height = height+'px';

	if (content.indexOf(".png") >= 0 || content.indexOf(".gif") >= 0 || content.indexOf(".jpg") >= 0) {
		var popContents = "<img src='"+content+"' style='cursor:pointer;' onclick='closePopup();' border=0>";
		if (caption != undefined) {
			var width2 = width-4;
			popContents += "<div id='pCaption' style='padding:3px;position:absolute;width:"+width2+"px;left:-1px;top:"+height+"px;background-color:black;color:white;font-weight:bold;text-align:center;font-size:10px;'>"+caption+"</div>";
			var height=height+20;
		}
		var param = "content="+popContents+"&pname="+pname+"&ptype=exercise";
		new Ajax.Updater("popUpBox", "/ajax/popup/" , {
			method:'post',
			parameters: param,
			asynchronous:true,
			evalScripts:true
		});
    pageTracker._trackEvent("popup","graphic",pname+" ("+controller+")");
    pageTracker._trackPageview("/"+controller+"/popup/graphic/"+pname);
	} else if (content.indexOf(".swf") >= 0) {
		var param = "content="+content+"&pname="+pname+"&width="+width+"&height="+height+"&ptype=notes";
		new Ajax.Updater("popUpBox", "/ajax/popup/" , {
			method:'post',
			parameters: param,
			asynchronous:true,
			evalScripts:true
		});
    	pageTracker._trackEvent("popup","notes",pname+" ("+controller+")");
   		pageTracker._trackPageview("/"+controller+"/popup/notes/"+pname);
	} else {
		$('popUpBox').innerHTML = content;
		pageTracker._trackEvent("popup","htmlContent ("+controller+")");
    pageTracker._trackPageview("/"+controller+"/popup/htmlContent");
	}
	
	$('popUpBox').style.marginLeft = ((getWinDim('x')-width)/2)+'px';
	$('popUpBox').style.marginTop =  ((getWinDim('y')-height)/2)+getScrollXY('y')+'px';
	//Effect.Grow('popUpBox');
	$('popUpBox').style.display = 'block';
	showCover(width,height);
}

function showInteractivity(id) {
	var path = 'content/animations/' + id + '/' + id + '.html';
	var interactivityWindow = window.open('/ajax/interactivity?path=' + path, 'interactivityWindow', 'width=722,height=502');
	interactivityWindow.focus();
}

function closePopup() {
	//Effect.Shrink('popUpBox');
	$('demoPlayer').innerHTML = "";
	$('popUpBox').innerHTML = '';
	$('popUpBox').style.display = 'none';
	$('screenCover').style.display = 'none';
	$('screenBorder').style.display = 'none';
}

function selectAProduct(state,whichSection) {
	if (state == "on") {
		$("dropDown"+whichSection).style.display = 'none';
		$("dropDownOff"+whichSection).style.display = 'inline';
		$("dropDownOpen"+whichSection).style.display = 'inline';
	}
	else {
		$("dropDown"+whichSection).style.display = 'inline';
		$("dropDownOff"+whichSection).style.display = 'none';
		$("dropDownOpen"+whichSection).style.display = 'none';
	}
}

function enterSubCode(index,state) {
	if (state == "on") {
		$("enterCodeOn"+index).style.display = 'none';
		$("enterCodeOff"+index).style.display = 'inline';
		Effect.Appear("enterSubCodePicker"+index, {duration:0.5});
	}
	else {
		$("enterCodeOn"+index).style.display = 'inline';
		$("enterCodeOff"+index).style.display = 'none';
		Effect.Fade("enterSubCodePicker"+index, {duration:0.5});
	}
}

function selectClass(index,state,whichSection) {
	if (state == "on") {
		$("dropDownSectionPicker"+index+whichSection).style.display = 'none';
		$("dropDownOffSectionPicker"+index+whichSection).style.display = 'inline';
		Effect.Appear("dropDownOpenSectionPicker"+index+whichSection, {duration:0.5});
	}
	else {
		$("dropDownSectionPicker"+index+whichSection).style.display = 'inline';
		$("dropDownOffSectionPicker"+index+whichSection).style.display = 'none';
		Effect.Fade("dropDownOpenSectionPicker"+index+whichSection, {duration:0.5});
	}
}

function swapImage(id,image,state) {
	if (state == "on") { var swapImg = image+"on.png"; }
	else 			   { var swapImg = image+".png"; }
	$(id).src = swapImg;
}

function validateViewName(value) {
	// allow only letters, numbers, and underscores
	var illegalChars = /\W/;
	if (value==null||value=="") {
		alert("Please enter a page name.");
		return false;
	} else if (illegalChars.test(value)) {
		alert("The page name contains illegal characters.");
		return false;
	} else {
		return true;
	}
	return false;
}

function validateImageFilename(filename) {
	// allow only valid image filenames
	var regexp = /[a-zA-Z0-9_-]+\.([jJ][pP][eE]?[gG]|[gG][iI][fF]|[pP][nN][gG])$/;
	if (regexp.test(filename)) {
		return true;
    } else {
    	alert("Please enter a valid JPEG, GIF or PNG image file path.")
    	return false;
    }
	return false;
}

function validateAssetFilename(filename) {
	// allow only valid image filenames
	var regexp = /[a-zA-Z0-9_-]+\.([jJ][pP][eE]?[gG]|[gG][iI][fF]|[pP][nN][gG]|[pP][dD][fF]|[dD][oO][cC][xX]?|[xX][lL][sS][xX]?|[pP][pP][tT][xX]?|[tT][xX][tT]|[sS][wW][fF]|[mM][oO][vV]|[hH][tT][mM][lL]?|[zZ][iI][pP])$/;
	if (regexp.test(filename)) {
		return true;
    } else {
    	alert("Please enter a valid PDF, DOC, DOCX, XLS, XLSX, PPT, PPTX, TXT, SWF, MOV, HTML, ZIP, JPEG, GIF, or PNG resource file path.")
    	return false;
    }
	return false;
}

function toggleTOCChapter(index,divId) {
	if ($(divId+'ch'+index).style.display == 'none') {
		Effect.SlideDown(divId+"ch"+index);
	}
	else {
		Effect.SlideUp(divId+"ch"+index);
	}
}

function replaceTemplate(field, templatePath) {
	if (field.value != "") {
		alert("Text area must be empty to insert this template.")
	} else {
		new Ajax.Request(templatePath,
		  {
		    method:'get',
		    onSuccess: function(transport){
		      var response = transport.responseText || "no response text";
		      field.value=response;
		    },
		    onFailure: function(){ alert('Error retrieving template') }
		  });
	}
}

function insertTemplate(field, templatePath) {
	if (field.value != "") {
		alert("Text area must be empty to insert this template.")
	} else {
		new Ajax.Request(templatePath,
	  {
	    method:'get',
	    onSuccess: function(transport){
	      var response = transport.responseText || "no response text";
	      //field.value=response;
	      insertAtCursor(field, response);
	    },
	    onFailure: function(){ alert('Error retrieving template') }
	  });
	}
}

//myField accepts an object reference, myValue accepts the text strint to add 
function insertAtCursor(myField, myValue) {
	if (myField == null) {
		alert("Cursor must be inside text box");
	} else {
		//IE support 
		if (document.selection) { 
			myField.focus();
			
			//in effect we are creating a text range with zero 
			//length at the cursor location and replacing it 
			//with myValue 
			sel = document.selection.createRange(); 
			sel.text = myValue; 
			
			// Highlight the inserted text
			// We'll use this as a 'dummy'
			var stored_sel = sel.duplicate();
			// Select all text
			stored_sel.moveToElementText( myField );
			// Now move 'dummy' end point to end point of original sel
			stored_sel.setEndPoint( 'EndToEnd', sel );
			// Now we can calculate start and end points
			selectionStart = stored_sel.text.length - myValue.length;
			selectionEnd = selectionStart + myValue.length;
			hiliteTA(myField, selectionStart, selectionEnd);
		}
		
		//Mozilla/Firefox/Netscape 7+ support 
		else if (myField.selectionStart || myField.selectionStart == '0') {
		
			//Here we get the start and end points of the 
			//selection. Then we create substrings up to the 
			//start of the selection and from the end point 
			//of the selection to the end of the field value. 
			//Then we concatenate the first substring, myValue, 
			//and the second substring to get the new value. 
			var startPos = myField.selectionStart; 
			var endPos = myField.selectionEnd; 
			var remainder = myField.value.substring(endPos, myField.value.length);
			myField.value = myField.value.substring(0, startPos)+ myValue.substring(0, myValue.length-1);
			
			// Generate a keypress to force the browser to scroll 
			// to the last character of the inserted text
			var ev = document.createEvent ('KeyEvents');
			ev.initKeyEvent('keypress', true, true, window,false, false, false, false, 0, myValue.charCodeAt(myValue.length-1));
			myField.dispatchEvent(ev);
			
			// Attach the remainder of the text
			myField.value = myField.value + remainder;
			
			// Highlight selected text
			myField.setSelectionRange(startPos, startPos+myValue.length);
		} else { 
			myField.value += myValue; 
		} 
	}
}

function calculateLines(s){
    var count = 0;
    
    for (var i = 0; i < s.length-1; i++){
        if (s.charCodeAt(i) == 13 && s.charCodeAt(i+1) == 10) count++;
    }		
    
    return count;
}	 
	  
function hiliteTA(ta,i,j){
    // Compensation is needed because the regex string subscripts include newline chars,
    // while the range's moveStart() and moveEnd() do not
    var compensation1 = calculateLines(ta.value.substring(0,i));
    var compensation2 = calculateLines(ta.value.substring(0,j));
		
    var r = ta.createTextRange();
		
    var r1,r2,r3;
		
    r1 = r.duplicate();
    r1.moveStart("character", i - compensation1);
    //alert(r1.text);
		
    r2 = r.duplicate();
    r2.moveStart("character", j - compensation2);
    //alert(r2.text);
		
    r3 = r.duplicate();
    //r3.collapse();
    r3.setEndPoint("StartToStart", r1);
    r3.setEndPoint("EndToStart", r2);
		
    r3.select();
}


function uploadImage() {
	var pars = "";
	var myAjax = new Ajax.Updater(
		{success: 'placeholder'}, 
		url, 
		{
			method: 'post', 
			parameters: pars, 
			onFailure: reportError
		});
}

/**
* Insert a tab at the current text position in a textarea
* Jan Dittmer, jdittmer@ppp0.net, 2005-05-28
* Inspired by http://www.forum4designers.com/archive22-2004-9-127735.html
* Tested on: 
*   Mozilla Firefox 1.0.3 (Linux)
*   Mozilla 1.7.8 (Linux)
*   Epiphany 1.4.8 (Linux)
*   Internet Explorer 6.0 (Linux)
* Does not work in: 
*   Konqueror (no tab inserted, but focus stays)
*/
function insertTab(event,obj) {
    var tabKeyCode = 9;
    if (event.which) // mozilla
        var keycode = event.which;
    else // ie
        var keycode = event.keyCode;
    if (keycode == tabKeyCode) {
        if (event.type == "keydown") {
            if (obj.setSelectionRange) {
                // mozilla
                var s = obj.selectionStart;
                var e = obj.selectionEnd;
                obj.value = obj.value.substring(0, s) + 
                    "\t" + obj.value.substr(e);
                obj.setSelectionRange(s + 1, s + 1);
                obj.focus();
            } else if (obj.createTextRange) {
                // ie
                document.selection.createRange().text="\t"
                obj.onblur = function() { this.focus(); this.onblur = null; };
            } else {
                // unsupported browsers
            }
        }
        if (event.returnValue) // ie ?
            event.returnValue = false;
        if (event.preventDefault) // dom
            event.preventDefault();
        return false; // should work in all browsers
    }
    return true;
}

/*
function toggleElement(obj, handleObj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
		$(handleObj).update('[<b> + </b>]');
	}
	else {
		el.style.display = '';
		$(handleObj).update('[<b> - </b>]');
	}
}
*/

function toggleInclude(num)
{
    if($('include'+num).hasClassName('bodyClosed'))
    {
        // open
        new Effect.BlindDown($('include'+num), { duration: .5});
        $('include'+num).addClassName('bodyOpen');
        $('include'+num).removeClassName('bodyClosed');
        $('toggle'+num).update('[<b> - </b>]');
    }
    else if($('include'+num).hasClassName('bodyEditedClosed'))
    {
        // open
        new Effect.BlindDown($('include'+num), { duration: .5});
        $('include'+num).addClassName('bodyOpen');
        $('include'+num).removeClassName('bodyEditedClosed');
        $('toggle'+num).update('[<b> - </b>]');
    }
    else
    {
        // close
        new Effect.BlindUp($('include'+num), { duration: .5});
        $('include'+num).addClassName('bodyEditedClosed');
        $('include'+num).removeClassName('bodyOpen');
        $('toggle'+num).update('[<b> + </b>]');
    }
}

function resize(textarea) {
	lines = textarea.value.split('\n');
	rows = lines.length - 1; // assume word wrap is off
	/*
	// use this code if word wrap is on
	rows=1;
	for (x=0;x < lines.length; x++) {
	 if (lines[x].length >= 80) rows+= Math.floor(lines[x].length/80);
	 }
	rows+= lines.length;
	*/
	
	fontSize = parseInt($(textarea).getStyle('font-size').replace(/px/,""));
	lineHeight = $(textarea).getStyle('line-height'); // px pt em %
	
	if (lineHeight == 'normal') {
		lineHeight = fontSize * 1.125; // assume .125em padding around chars
	} else if (lineHeight.search(/%/) != -1) {
		lineHeight = parseInt(lineHeight.replace(/%/,"")) * fontSize/100;
	} else if (lineHeight.search(/em/) != -1) {
		lineHeight = parseInt(lineHeight.replace(/em/,"")) * fontSize;
	} else if (lineHeight.search(/px/) != -1) {
		lineHeight = parseInt(lineHeight.replace(/px/,""));
	} else if (lineHeight.search(/pt/)!= -1) {
		lineHeight = parseInt(lineHeight.replace(/pt/,""));
	} else {
		lineHeight = parseInt(lineHeight) * fontSize;
	}
	
	newHeight = rows * lineHeight + 3 * lineHeight;
	curHeight = parseInt($(textarea).getStyle('height').replace(/px/,""));
	if (newHeight > curHeight)
	{
		//alert("rows = " + rows + " newheight = " + newHeight + "height = " + curHeight);
		$(textarea).setStyle({height: newHeight + 'px'});
	}
}

function toggleWrap(textareaid) {
	var form = $(document.forms[0]);
 	if (Prototype.Browser.WebKit) {
		var elements =  $(form[textareaid]);
	 	if (elements[0]) {
	 		// if there are multiple textareas
			for ( var i=0; i<elements.length; i++ ) {
				toggleWrapSingle(elements[i])
			}
	 	} else {
	 		// if there is only one textarea
	 		toggleWrapSingle(elements);
	 	}
	 	$(elements[1]).focus();
	} else {
		form.writeAttribute("action","toggleWrap");
		form.submit();
	}
}

function toggleWrapSingle(textareaid) {
	if ($(textareaid).readAttribute('wrap') == 'off') {
			$(textareaid).writeAttribute("wrap","virtual");
		} else {
			$(textareaid).writeAttribute("wrap","off");
		}
		$(textareaid).focus();
}

// Removes leading whitespaces
function LTrim( value ) {
  if (value != undefined) {
  	var re = /\s*((\S+\s*)*)/;
  	return value.replace(re, "$1");
  }	
  
}

// Removes ending whitespaces
function RTrim( value ) {
  if (value != undefined) {
  	var re = /((\s*\S+)*)\s*/;
  	return value.replace(re, "$1");
  }
}

// combined trim
function Trim(value) {
  if (value != undefined) {
    return LTrim(RTrim(value));
  }
}

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

/*
function deleteView(controller,view,elementToRemove) {
	if(confirm('Are you sure you want to delete '+controller+"/"+view+" ?")) {
		new Ajax.Request("/ajax/deleteview", {
			method:'post',
			parameters: 'c='+controller+'&v='+view,
			asynchronous:true,
			evalScripts:true,
			onSuccess: function(transport) {
				var item = transport.responseText.evalJSON();
				//$('ajaxMessage').update(item.message);
				if (item.success) {
					$(elementToRemove).remove();
				}
			},
			onFailure: function() {
				$('ajaxMessage').update("Connection error: unable to delete file.");
			}
		});
	}
}
*/

function deleteView(path,elementToRemove) {
	if(confirm('Are you sure you want to delete '+path+" ?")) {
		new Ajax.Request("/ajax/deleteview", {
			method:'post',
			parameters: 'path='+path,
			asynchronous:true,
			evalScripts:true,
			onSuccess: function(transport) {
				var item = transport.responseText.evalJSON();
				//$('ajaxMessage').update(item.message);
				if (item.success) {
					$(elementToRemove).remove();
				}
			},
			onFailure: function() {
				$('ajaxMessage').update("Connection error: unable to delete file.");
			}
		});
	}
}

function createView(controller,dir,name) {
	//alert('creating c: '+controller+', name: '+name+', dir: '+dir);
	if (validateViewName(name)) {
		if ($(name)) {
			new Effect.Highlight(name, { startcolor: '#F89A4F',endcolor: '#ffffff' });
			$('templateName').value = "";
		} else {
			new Ajax.Request("/ajax/newview", {
				method:'post',
				parameters: 'templateDir='+dir+'&templateName='+name,
				asynchronous:true,
				evalScripts:true,
				onSuccess: function(transport) {
					var item = transport.responseText.evalJSON();
					//$('ajaxMessage').update(item.message);
					if (item.success) {
						var escapedDir = dir.replace(/\\/g,"\\\\");
						var escapedPath = escapedDir + "\\\\" + name + ".cfm";
						var cfinclude = '&lt;cfinclude template="/#viewDirectory#/'+controller+'/'+name+'.cfm"&gt';
						$('ajaxMessage').update('To include the template you created in another page, copy this code: '+cfinclude);
						if (controller.search(/\//) != -1) {
							// do not allow edit for templates in subdirectories of views
							$('templatesTable').update($('templatesTable').innerHTML + '<tr id="'+name+'"><td>'+name+'</td><td></td><td><a href="" onClick=" procLink('+"'"+escapedPath+"'"+'); return false;">edit</a></td><td><a href="" onClick="deleteView('+"'"+escapedPath+"','"+name+"'"+'); return false;">delete</a></td></tr>');
						} else {
							$('templatesTable').update($('templatesTable').innerHTML + '<tr id="'+name+'"><td>'+name+'</td><td><a href="/'+controller+'/'+name+'">view</a></td><td><a href="/page/edit?c='+controller+'&v='+name+'">edit</a></td><td><a href="" onClick="deleteView('+"'"+escapedPath+"','"+name+"'"+'); return false;">delete</a></td></tr>');
						}
						new Effect.Highlight(name, { startcolor: '#F89A4F',endcolor: '#ffffff' });
						//document.forms[0].submit();
					}
					//new Effect.BlindUp($('newFileHTML'), { duration: .1});
					$('templateName').value = "";
				},
				onFailure: function() {
					$('ajaxMessage').update("Connection error: unable to delete file.");
				}
			});
		}
	}
}
	
function procLink(templatePath) {
	$('templatePath').value = templatePath;
	$('createWrapperForm').submit();
}
	
	
function enterKeyPressed(e) {
	var key;
	
	if(window.event)
		 key = window.event.keyCode;     //IE
	 else
		 key = e.which;     //firefox

	 if(key == 13) {
		return true;
	 }
	else
		 return false;
}

// product management
function togglePM(a) {
  if ( $("pgControl"+a).innerHTML.indexOf("expand.png") > 0) {
    Effect.BlindDown("productGroup"+a);
    $("pgControl"+a).innerHTML = "<img src='/images/interface/buttons/contract.png'>";
  }
  else {
    Effect.BlindUp("productGroup"+a);
    $("pgControl"+a).innerHTML = "<img src='/images/interface/buttons/expand.png'>";
  }
}

function refreshdb(a) {
  if (a == undefined) var a = 'dBr=1';
	new Ajax.Request("/ajax/reloadproducts", {
				asynchronous:true,
				evalScripts:true,
		    onSuccess: function(transport){
		      window.location="/product/index/?"+a;
		    },
        onFailure: function(){ alert('Error refreshing dB.') }
  });
}

function createNewWebID() {
  $('webIDList').style.display = 'none';
  $('webIDInput').style.display = 'block';
}

function swapDiv(a,b) {
  $(a).style.display = 'none';
  $(b).style.display = 'block';
}
// end product management

//test exams
    curQ = 1;
    function testCheckAns(qid,ans) {
    	new Ajax.Updater("a", "/ajax/testexamCheck/?qid="+qid+"&ans="+ans , {
    		asynchronous:true,
    		evalScripts:true,
    		onSuccess: function(transport) {
    		  $('questionBox').innerHTML = '<img src="/images/interface/icons/loading.gif" align="absmiddle"> Checking...';
    		  var ut = setTimeout("updateTest("+qid+","+ans+")",1000);
        }
    	});
    }
    
    function updateTest(qid,ans) {
	    var curScore = parseInt($("sc").innerHTML);
		  var result = Trim(($('a').innerHTML));
		  if (result.indexOf("reset") == 0) {
		    testCheckAns(qid,ans);
		  }
		  else {
		    if (result.indexOf("true") == 0) {
		      var ns = parseInt(parseInt(curScore)+1);
          $("sc").innerHTML = ns;
		    }
		    if (curQ >= 10) {
          curQ = 1;
		      scoreTest();
		    }
		    else {
  		    curQ = curQ+1;
   		    $('questionBox').innerHTML = $('q'+curQ).innerHTML;
   		  }
      }
	    $('a').innerHTML = 'reset';
    }
    
    function scoreTest() {
      var score = Trim($('sc').innerHTML);
      if (score > 7) {
        wProduct = "<div style='text-align:center;font-weight:bold;'>Thinkwell's College Algebra</div>";
        wProductPic = "<div style='text-align:center;padding:10px;'><img style='border:1px solid black;' src='http://www.thinkwell.com/images/interface/productshots/collegealgebra-online.gif'></div>";
      }
      else if (score > 3) {
        wProduct = "<div style='text-align:center;font-weight:bold;'>Thinkwell's Intermediate Algebra</div>";
        wProductPic = "<div style='text-align:center;padding:10px;'><img style='border:1px solid black;' src='http://www.thinkwell.com/images/interface/productshots/intermediatealgebra-online.gif'></div>";
      }
      else {
        wProduct = "<div style='text-align:center;font-weight:bold;'>Thinkwell's Beginning Algebra</div>";
        wProductPic = "<div style='text-align:center;padding:10px;'><img style='border:1px solid black;' src='http://www.thinkwell.com/images/interface/productshots/beginningalgebra-online.gif'></div>";
      }
      $('questionBox').innerHTML = "<div style='text-align:center;background-color:#ff973e;padding:5px;font-weight:bold;'>You got "+score+" out of 10 correct!</div><br/>";
      $('questionBox').innerHTML += "<div style='text-align:center;'>Based on this result we recommend</div>";
      $('questionBox').innerHTML += wProduct + wProductPic;
      $('questionBox').innerHTML += "<br/><div style='text-align:center;font-weight:bold;'><img src='/images/interface/buttons/close.png' style='cursor:pointer;' onclick='closePopup();'></div>";
    }
//end test exams

	function promoOpen(block,pid) {
		Effect.Appear(block+pid,{from:0,to:.7,duration:.5});
		Effect.Appear(block+pid+'inside',{from:0,to:1,duration:.5});	
		$(block+pid).style.top = '1px';
		$(block+pid).style.left = '1px';
		$(block+pid).style.marginLeft = ((getWinDim('x')-400)/2)+'px';
		$(block+pid).style.marginTop =  ((getWinDim('y')-400)/2)+getScrollXY('y')+'px';
		$(block+pid+'inside').style.top = '1px';
		$(block+pid+'inside').style.left = '1px';
		$(block+pid+'inside').style.marginLeft = ((getWinDim('x')-400)/2)+'px';
		$(block+pid+'inside').style.marginTop =  ((getWinDim('y')-400)/2)+getScrollXY('y')+'px';
	}
	
	function promoClose(block,pid) {
		$(block+pid).style.display = 'none';
		$(block+pid+'inside').style.display = 'none';
	}
	
	function promoToc(pid) {
		Effect.Appear('promoToc'+pid,{from:0,to:.7,duration:.5});
		Effect.Appear('promoToc'+pid+'inside',{from:0,to:1,duration:.5});	
		$('promoToc'+pid).style.top = '1px';
		$('promoToc'+pid).style.left = '1px';
		$('promoToc'+pid).style.marginLeft = ((getWinDim('x')-400)/2)+'px';
		$('promoToc'+pid).style.marginTop =  ((getWinDim('y')-400)/2)+getScrollXY('y')+'px';
		$('promoToc'+pid+'inside').style.top = '1px';
		$('promoToc'+pid+'inside').style.left = '1px';
		$('promoToc'+pid+'inside').style.marginLeft = ((getWinDim('x')-400)/2)+'px';
		$('promoToc'+pid+'inside').style.marginTop =  ((getWinDim('y')-400)/2)+getScrollXY('y')+'px';
	}
	
	function closePromoToc(pid) {
		$('promoToc'+pid).style.display = 'none';
		$('promoToc'+pid+'inside').style.display = 'none';
	}
	
	function submitSurvey (passUserId) {
	    // AJAX: submit the survey
	    q1Answers = '';
	    q2Answer  = '';
	    q3Answer  = '';
	    len = document.surveyForm.question1.length;
	    for (i=0;i<len;i++) {
	    	if (document.surveyForm.question1[i].checked) {
	    		q1Answers = q1Answers + document.surveyForm.question1[i].value + ',';
	    	}
	    }
	    if (q1Answers == '') {
	    	alert ('Please select one or more answers for the first question.');
	    } else {
	    	q1Answers = q1Answers.substr (0, (q1Answers.length - 1));
	    	len = document.surveyForm.question2.length;
	    	for (i=0;i<len;i++) {
		    	if (document.surveyForm.question2[i].checked) {
		    		q2Answer = document.surveyForm.question2[i].value;
		    	}
		    }
		    if (q2Answer == '') {
		    	alert ('Please select an answer for the second question.');
		    } else {
				len = document.surveyForm.question3.length;
		    	for (i=0;i<len;i++) {
			    	if (document.surveyForm.question3[i].checked) {
			    		q3Answer = document.surveyForm.question3[i].value;
			    	}
			    }
			    if (q3Answer == '') {
			    	alert ('Please select an answer for the third question.');
			    } else {
				    new Ajax.Request ('/ajax/submitSurvey', {
						method:'post',
						parameters: {surveyUserId:passUserId,question1:q1Answers,question2:q2Answer,question3:q3Answer},
						onSuccess: function(transport) {
							document.signInForm.submit ();
						}
			 		});
			 	}
		 	}
		}
	}
	
