var browser;
jQuery.each(jQuery.browser, function(i, val){
    if (i == "mozilla" && jQuery.browser.version.substr(0, 3) == "1.9") 
        browser = 'mozilla';
    else if (i == "msie") 
        browser = 'msie';
    else if (i == "safari") 
        browser = 'safari';
    else if (i == "opera") 
        browser = 'opera';
});

$('document').ready(function() {
	$('#parent_cstCnt').hide();
		var productName = $("#productName").val();
		var cntLoc = $("#cntLoc").val();
		var types = $("#types").val();
		var roles = $("#roles").val();
		var groups = $("#groups").val();
		var al = $("#cal").val();
		var orgId = $("#orgId").val();
		var random = $("#random").val();
		var cntNodeIds = $("#cntNodeIds").val();
		var session = $("#session").val();
	   if(session != undefined && session == 'true'){
		   fn_loadCustomContnet(productName,cntLoc,random,types,groups,al,orgId,roles,cntNodeIds,'customContent');
	   }
	   fn_pngIEFix();
		
});

/*
  Function to correctly handle PNG transparency in Win IE 5.5 & 6.
  http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
*/
function fn_pngIEFix() {
  var arVersion = navigator.appVersion.split("MSIE")
  var version = parseFloat(arVersion[1])

  if ((version >= 5.5) && (document.body.filters)) 
  {
     for(var i=0; i<document.images.length; i++)
     {
      var img = document.images[i]
      var imgName = img.src.toUpperCase()
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
      {
         var imgID = (img.id) ? "id='" + img.id + "' " : ""
         var imgClass = (img.className) ? "class='" + img.className + "' " : ""
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
         var imgStyle = "display:inline-block;" + img.style.cssText 
         if (img.align == "left") imgStyle = "float:left;" + imgStyle
         if (img.align == "right") imgStyle = "float:right;" + imgStyle
         if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
         + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
         + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
         img.outerHTML = strNewHTML
         i = i-1
      }
   }
  }
}



// method to load the Custom Content
function fn_loadCustomContnet(productName,cntLoc,random,types,groups,al,orgId,roles,cntNodeIds,divId) {
	var imgFPath ='';
	var dataString = '';
	dataString = "productName=" + productName + "&contentLoc=" +cntLoc + "&random=" +random;
	
	if(types != undefined && types != ''){
		dataString += "+&types=" +types 
	}
	if(groups != undefined && groups != ''){
		dataString += "+&groups=" +groups 
	}
	if(al != undefined && al != ''){
		dataString += "+&academiclevels=" +al 
	}
	if(orgId != undefined && orgId != ''){
		dataString += "+&orgId=" +orgId 
	}
	if(roles != undefined && roles != ''){
		dataString += "+&roles=" +roles 
	}
	if(cntNodeIds != undefined && cntNodeIds != ''){
		dataString += "+&cntNodeIds=" +cntNodeIds 
	}
	if(groups != undefined && groups != ''){
		$.getJSON('/getCustomContent?np=/customContent.json&'+dataString,
			function(jsonObject, status) {
				if (status == "success") {
						if(jsonObject != null && jsonObject != ''){
							var roleCode = jsonObject[0].roleCode;
							var html = '/cc';
							path =  html+jsonObject[0].customCntPath;
							var pathcopy =  html+jsonObject[0].customCntPath;
							$.get(path, function(data) {
								
								$('#' +divId).html(data);
								$('#' + divId + ' img').each(function() {
										
									var imgSrc = $(this).attr("src");
									var imgAlt = $(this).attr("alt");
									if (imgSrc != undefined ) {
										pathcopy = setImageSrc(imgSrc, pathcopy);
										$(this).attr("src", pathcopy);
										if (roleCode == 'TEACHER' && imgAlt == 'Site of the Day icon') {
											$(this).attr("src","/images/right/cod_teacher.gif");
										}
										if (roleCode != 'TEACHER' && imgAlt == 'Site of the Day icon') {
											$(this).attr("src","/images/right/cod_all.gif");
										}
										if (imgAlt == 'Search'){
										   $(this).attr("src",'/images/btns/search.gif');
										}
									}
									
									});
									$('#parent_cstCnt').show();
						   });
						 }
					}
			}
	);
	}
}
function setImageSrc(imgSrc ,imgPath){
	if (imgSrc != undefined && imgPath != undefined) {
		var asd = imgSrc.split("/");
		var imgName = asd[asd.length-1];
		imgPath = imgPath+imgName;
		return imgPath;
	}
}
// for opening a help popup window.  Pass in file name and anchor
function openHelpWin(myfile,myanchor) {
   w = window.open("/html/help" + myfile + myanchor, "helpwin",
    "height=600,width=770,resizable=no,toolbar=no," +
    "status=no,location=no,scrollbars=yes");
}
function openPopWin(filepath,h,w) {
   w = window.open(filepath, "legend",
    "height=" + h + ", width=" + w + ",resizable=no,toolbar=no," +
    "status=no,location=no,scrollbars=no");
}
function openLegend(homepage) {
	  w = window.open("/goPage?np=/results/resultLegend_ie6.ftl&pp=/results/resultLegend_ie6.ftl&homepage="+homepage, "legend",
	  "height=780,width=700,resizable=no,toolbar=no," +
	  "status=no,location=no,scrollbars=auto");
	  w.focus();
}
/****************************************************
 * function for admin usermanagement page. 
 * Grabs status value from dropdown
 *
 */
function fn_adminUserStatus(userid, myselect) {	
	var currentStatus = $(myselect + ' option:selected').val();
	var hidStatusArray = $('#id_userStatusArray').val();	
	
	if (hidStatusArray != '') {
		adminStatus = hidStatusArray + ',' + userid +'_' + currentStatus;
	} else {
		adminStatus = userid + '_' + currentStatus;	
	}
	
	$('#id_userStatusArray').val(adminStatus);
}

/****************************************************
* function for admin usermanagement page. 
* Grabs role value from dropdown
*
*/
var changedRolesUsers = new Array();
function fn_adminUserRole(userid, myselect) {	
	var currentRole = $(myselect + ' option:selected').val();
	adminRole = '';
	
	changedRolesUsers[userid] = currentRole;
	var hidRoleArray = $('#id_userRoleArray').val();

	for (var user in changedRolesUsers) {
		if (adminRole != '') {
			adminRole = adminRole + "," + user + '_' + changedRolesUsers[user];
		} else {
			adminRole = user + '_' + changedRolesUsers[user];
		}
	}	
	
	$('#id_userRoleArray').val(adminRole);
}

/****************************************************
 * function for pref homepage.  Disable Channels 
 * for standards
 */
function fn_prefHomeSTDOnOff(idHomePage, idChannels) {
   if ($(idHomePage + ' option:selected').val() == 'S') {
     $(idChannels).attr('disabled','disabled');
   } else {
     $(idChannels).attr('disabled',false);   
   }
}


/***
 * Purpose Used to Redirect clicking of standards to appropriate page
 */
var isCanadaLoaded = false;
function redirectStd(element, al){
    if (window.RegExp && window.encodeURIComponent) {
        var qe = document.kwdbar.query.value;
		if(!qe){
			qe=$("#id_searchKeyword").text();
		}
        if (qe != null && jQuery.trim(qe).length > 0) {
            setStdPref();			
			if(browser == 'msie'){
				qe = encodeURI(qe);
			}			
            //redirecting to the stds result page. 
            element.href ="/standards/search?pp=/standards/results_ie6.ftl&np=/standards/results_ie6.ftl&al=Standards&HOMEPAGE=S&query=" + qe + "&limit=8&start=1&grade=" + al + "&context=" + standards;
        }
    }
    return 1;
}

function setStdPref(){
    var dataString = 'pref_code_1=HOMEPAGE&pref_value_1=S';
    //setting the pref values to standards
    $.ajax({
        dataType: 'xml',
        type: "get",
        timeout: 300000,
        url: "/goPage",
        data: dataString,
        async: false    
    }); 
	setContextId();  
}

function setContextId(){
	 $.ajax({
        dataType: "json",
        type: "get",
        timeout: 30000,
        url: '/standards/nodes?np=/standards/nodes.json&pp=/standards/nodes.json',
        success: getStandardsPrefId,
        async: false
    });
}

function getStandardsPrefId(nodes, status){
    var temp = standards;
    var isCanadian = false;
    if (!standards) {
        temp = "National Standards";
    }
    else if (getCanadianDBName(standards) != standards) {
        temp = "Canada";
        if (isCanadaLoaded == true) {
            temp = getCanadianDBName(standards);
        }
        isCanadian = true;
    }
    if (status == "success") {
        for (var i = 0; i < nodes.length; i++) {
            if (nodes[i].label == temp) {
                temp = nodes[i].id;
                break;
            }
        }
    }
    
    if (isCanadian==true && isCanadaLoaded == false) {
        isCanadaLoaded = true;
        $.ajax({
            dataType: "json",
            type: "get",
            timeout: 30000,
            url: '/standards/nodes/' + temp + '?np=/standards/nodes.json&pp=/standards/nodes.json',
            success: getStandardsPrefId,
            async: false
        });
    }
    else {
        standards = temp;
    }
}

//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(value, govId, pageSize){ 	
	var submitForm = '<form name="inactiveForm" method="post" action="/saveUser">'+
		'<input type="hidden" name="nextService" value="/admin/listUsers?np=/admin/user_management_ie6.ftl&' + 
		'pp=/admin/user_management_ie6.ftl&actflag=1&userCountLimit=' + pageSize + '"/>' +
		'<input type="hidden" name="userStatusArray" value="'+value+'"/> '+
		'<input type=hidden name="np" value="/admin/user_management_ie6.ftl"/>'+
		'<input type=hidden name="govCode" value="'+govId+'" />'+
		'<input type=hidden name="actflag" value="1" />' +
		'<input type=hidden name="userCountLimit" value="'+pageSize+'" />'+
		'</form>';
	document.getElementById("inactive").innerHTML = submitForm;
	document.inactiveForm.submit();
}

/**
 * Method to show the registration code history table.
 * 
 */
function showRegHistory(){
	$("#regHistory").show();
}

/**
 * Bind the object with function scope.
 */ 
Function.prototype.bind = function()
{
  var method = this;
  var args = Array.prototype.slice.call(arguments);
  var object = args.shift();
  return function()
  {
    return method.apply(object,args.concat(args));
  };
};

/**
 * Method to get the Query String value for form.
 */
function getAjaxFormData(formId)
{   
    var oForm;

	if(typeof formId == 'string'){
		// Determine if the argument is a form id or a form name.
		// Note form name usage is deprecated by supported
		// here for legacy reasons.
		oForm = (document.getElementById(formId) || document.forms[formId]);
	}
	else if(typeof formId == 'object'){
		// Treat argument as an HTML form object.
		oForm = formId;
	}
	else{
		return;
	}
	var formData = getFormData(oForm);
	return formData;
}


// Iterate over the form elements collection to construct the
		// label-value pairs.
function getFormData(oForm){
    var oForm, oElement, oName, oValue, oDisabled;
    var data = [], item = 0, i, len, j, jlen, opt;
	var utf8Coder = new Utf8();
    for (i = 0, len = oForm.elements.length; i < len; ++i) {
        oElement = oForm.elements[i];
        oDisabled = oElement.disabled;
        oName = oElement.name;
        
        // Do not submit fields that are disabled or
        // do not have a name attribute value.
        if (!oDisabled && oName) {
            oName = utf8Coder.encode(oName) + '=';
            oValue = utf8Coder.encode(oElement.value);
            
            switch (oElement.type) {
                // Safari, Opera, FF all default opt.value from .text if
                // value attribute not specified in markup
                case 'select-one':
                    if (oElement.selectedIndex > -1) {
                        opt = oElement.options[oElement.selectedIndex];
                        data[item++] = oName +
                        utf8Coder.encode((opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
                    }
                    break;
                case 'select-multiple':
                    if (oElement.selectedIndex > -1) {
                        for (j = oElement.selectedIndex, jlen = oElement.options.length; j < jlen; ++j) {
                            opt = oElement.options[j];
                            if (opt.selected) {
                                data[item++] = oName +
                                utf8Coder.encode((opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
                            }
                        }
                    }
                    break;
                case 'radio':
                case 'checkbox':
                    if (oElement.checked) {
                        data[item++] = oName + oValue;
                    }
                    break;
                case 'file':
                // stub case as XMLHttpRequest will only send the file path as a string.
                case undefined:
                // stub case for fieldset element which returns undefined.
                case 'reset':
                // stub case for input type reset button.
                case 'button':
                    // stub case for input type button elements.
                    break;
                case 'submit':
                    if (hasSubmit === false) {
                        if (this._hasSubmitListener && this._submitElementValue) {
                            data[item++] = this._submitElementValue;
                        }
                        else {
                            data[item++] = oName + oValue;
                        }
                        
                        hasSubmit = true;
                    }
                    break;
                default:
                    data[item++] = oName + oValue;
            }
        }
    }
	return data.join('&');
}

var OverlayDimmer = function(element){
	this.element = undefined;

    if (typeof element == 'string') 
	{
        this.element = document.getElementById(element);
    }
    else if (typeof element == 'object') 
	{
        this.element = element;
    }
	if(this.element){
		this.offset = $(this.element).offset();		
		this.offset.height = $(this.element).height();
		this.offset.width = $(this.element).width();
	}
        

}
OverlayDimmer.prototype = {
    show: function(){
    	this.createdEl = $("<div id='overlay'>&nbsp;</div>")
			.css('left',this.offset.left-2)
			.css('top',this.offset.top-2)
			.css('height',this.offset.height + 4)
			.css('width',this.offset.width + 4)
			.addClass("overlayDimmer")
			.addClass("transparent_class");
		
		this.loadingDiv = $("<div id='loadingDiv'>&nbsp;</div>")
			.css('left',this.offset.left)
			.css('top',this.offset.top)
			.css('height',this.offset.height)
			.css('width',this.offset.width)
			.css("position","absolute")
			.css("z-index","1000");
			
		var loadImage = $("<img/>&nbsp;</img>")
			.attr('src',"/images/ajax-loader-small.gif")
			.attr('alt',"Loading")
			.css("left" ,(this.offset.width/2) - 8)
			.css("top" ,(this.offset.height/2) - 8)
			.css("position", "absolute");
			
		$(this.loadingDiv).html(loadImage);
		$(this.element).before(this.createdEl);
		$(this.element).before(this.loadingDiv);
    },
    
    hide: function(){
    	$(this.createdEl).remove();
		$(this.loadingDiv).remove();
    }
}

/****************************************************/
/** Function to display the Right Menu bar */
function showRightBar(){ 
	$('#id_body').attr("class", "cs_nTContent cs_floatLT");
	$('#id_body').attr("style", "width: 618px;");
	$('#id_rightbar').css("visibility", "visible");
	$('#id_rightbarControl').attr("src", "/images/btns/hide.gif");
	$('#id_rightbarControl').attr("title","Hide Features & Tools");
	$('#id_rightbarControl').attr("alt","Hide Features & Tools");
	$('.cs_rightbar').unbind("click").bind("click", function(){hideRightBar()});
		document.cookie = "rightbar=visible; path=/";
}


/****************************************************/
/** Function to hide the Right Menu bar */
function hideRightBar(){	
	$('#id_body').attr('class','cs_ntContent_wide cs_floatLT');
	$('#id_body').attr("style", "width: 750px;");
	$('#id_rightbar').css('visibility','hidden');
	$('#id_rightbarControl').attr("src","/images/btns/show.gif");
	$('#id_rightbarControl').attr("title","Show Features & Tools");
	$('#id_rightbarControl').attr("alt","Show Features & Tools");
	$('.cs_rightbar').unbind("click").bind("click", function() {showRightBar()});
		document.cookie = "rightbar=hidden; path=/";
}


/****************************************************/
/** Function to keep the delete (expire) a cookie */	

function deleteCookie(cookieName){
	var ary_cookie = document.cookie.split(';'); 
	for(var i=0;i < ary_cookie.length;i++) {
		var cookie_value = ary_cookie[i];
		while (cookie_value.charAt(0)==' ')
			cookie_value = cookie_value.substring(1,cookie_value.length); 		
			if (cookie_value.indexOf(cookieName) == 0) {				
				document.cookie = cookieName + "=; path=/" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
			}
	}	
}

/****************************************************/
/** Function to keep the Right Menu bar state (hidden or visible) as the user switches tabs */	
function rightBarController() { 
	var rtbar = "visible";	
	var cookie_name = "rightbar="; 
	var ary_cookie = document.cookie.split(';'); 
	for(var i=0;i < ary_cookie.length;i++) {
		var cookie_value = ary_cookie[i];
		while (cookie_value.charAt(0)==' ')
			cookie_value = cookie_value.substring(1,cookie_value.length); 
			if (cookie_value.indexOf(cookie_name) == 0) {
				rtbar=cookie_value.substring(cookie_name.length,cookie_value.length);					
				if ((rtbar=="hidden") )
					{ hideRightBar();} else {showRightBar(); }
			return;
			}			
		} 
	//hide rightbar from Elementary Students
	if (js_academiclevel != "Elementary" || js_userrole.toUpperCase() != "STUDENT")
	{
		showRightBar();
	} else {
		hideRightBar();
	}
} 

/****************************************************/
/** Function to build Teacher Tools link in right bar */	

function buildTeacherToolsLink(al,ttNodeId){
	if (ttNodeId != ""){
		if ($("#ttlink") != null){			
			var tthtml = '<a href="/goSubject?np=/subjectresults_ie6.ftl&nodeID='+ttNodeId+'&al='+al+'&maxSites=8">Teacher Tools</a>'
			$("#ttlink").attr("innerHTML", tthtml);
		}
	} else {
	var ttNodeId = "";	
	var cookie_name = "ttNode="; 
	var ary_cookie = document.cookie.split(';'); 
	for(var i=0;i < ary_cookie.length;i++) {
		var cookie_value = ary_cookie[i];
		while (cookie_value.charAt(0)==' ')
			cookie_value = cookie_value.substring(1,cookie_value.length); 
			if (cookie_value.indexOf(cookie_name) == 0) {
				ttNodeId=cookie_value.substring(cookie_name.length,cookie_value.length);					
				if ($("#ttlink") != null){
					var tthtml = '<a href="/goSubject?np=/subjectresults_ie6.ftl&nodeID='+ttNodeId+'&al='+al+'&maxSites=8">Teacher Tools</a>'
					$("#ttlink").attr("innerHTML", tthtml);
				}
			return;
			}			
		}
	}
}


// Bind the global function for ajax request completed.  
$(window).bind("ajaxError", function(event, response, settings) {});

function goPage() {
	var type = $("#contactType").val();
    var selected = $("#contactType option:selected");  
	var value = selected.val();
	var text = selected.text();	
	var proId = $("#proId").val();
	if(type == 'A') {
		document.location.href = "/goNSS?np=/help/contactus/access_ie6.ftl&pp=/help/contactus/access_ie6.ftl&categoryId="+type+"&pass="+proId;
	} else if(type == 'F') {
		document.location.href = "/goNSS?np=/help/contactus/subscription_ie6.ftl&pp=/help/contactus/subscription_ie6.ftl&pass="+proId;
	} else if(type == 'S') {
		document.location.href = "/goNSS?np=/help/contactus/search_ie6.ftl&pp=/help/contactus/search_ie6.ftl&pass="+proId;
	} else if(type == 'E') {
		document.location.href = "/contactUs?np=/help/contactus/enhancement_ie6.ftl&pp=/help/contactus/enhancement_ie6.ftl&category="+type+"&proId="+proId;
	} else if(type == 'T') {
		document.location.href = "/goNSS?np=/help/contactus/training_ie6.ftl&pp=/help/contactus/training_ie6.ftl&pass="+proId;
	} else if(type == 'O') {
		document.location.href = "/goNSS?np=/help/contactus/other_ie6.ftl&pp=/help/contactus/other_ie6.ftl&pass="+proId;
	}
}
 
//reset the parameters necessary for Keyword search
function submitSearch(searchAction, method, prevSearchType, curSearch, pagelimit) {
	if (curSearch == "IMAGE"){
		if (prevSearchType == "PERSON"){
			document.kwdbar.action = searchAction;
			document.kwdbar.method = method;
			document.kwdbar.np.value = "/webresults_ie6.ftl";
			document.kwdbar.pp.value = "/webresults_ie6.ftl";			
			document.kwdbar.id_query.name = "query";
			document.kwdbar.id_level.name = "al";		
		} 
			document.kwdbar.searchType.value = "IMAGE";
			document.kwdbar.limit.value = "9";
			document.kwdbar.start.value = "1";			
		
	}
	if (curSearch == "WEBCONTENT"){	
		if (prevSearchType == "PERSON"){
			document.kwdbar.action = searchAction;
			document.kwdbar.method = method;
			document.kwdbar.np.value = "/webresults_ie6.ftl";
			document.kwdbar.pp.value = "/webresults_ie6.ftl";
			//document.kwdbar.searchType.value = "WEBCONTENT";
			document.kwdbar.id_query.name = "query";
			document.kwdbar.id_level.name = "al";
		} 
			document.kwdbar.searchType.value = "WEBCONTENT";
			document.kwdbar.nextService.value = "/goPage?np=/home_ie6.ftl&pp=/home_ie6.ftl";
			document.kwdbar.limit.value = pagelimit;
			document.kwdbar.start.value = "1";			
		
	}
	document.kwdbar.submit();
}
//Checks if the user has entered a keyword and submits Image search
//Launches Image Index if no keyword was entered
function submitImageSearch(searchAction, method, prevSearchType, curSearch) {
	if (document.kwdbar.id_query.value == ""){
		window.location = "/goPage?np=/images/imageIndex_ie6.ftl&pp=/images/imageIndex_ie6.ftl&searchType=IMAGE";
	} else {
		submitSearch(searchAction, method, prevSearchType, curSearch) 
	}
}

//set the NodeIDs field for Search In Context
function setNodeIDs(field) {
	if (field.checked == true){
		$("#id_nodeIDs").attr("value", field.value);
	} else {
		$("#id_nodeIDs").attr("value", "");
	}
}

function checkNumberOnly(e){
    //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && e.which != 13 && (e.which < 48 || e.which > 57)) {
        //display error message
        return false;
    }
}

function goFamousPersonPage(){
    var query = $("#id_query").val();
    var href = "/searchFamousPerson?np=/famous/index_ie6.ftl&pp=/error_ie6.ftl&searchType=PERSON";
    if (query && jQuery.trim(query).length > 0) {
		if(browser=='msie'){
			query = encodeURI(query);
		}
		
        href = "/searchFamousPerson?np=/famous/results_ie6.ftl&pp=/famous/results_ie6.ftl&searchType=PERSON&goFPersonSearch=Y&start=1&limit=50&level=" + js_academiclevel + "&name=" + query;
    }
    window.location = href;
}


// shows the 21st Century divs
function display21cDiv(showDivId, selDivId, al){
	var htmlstr = '';
	var contstr;
	var htmlstrbegin = ''; 
	var htmlstrclose = '</div></div><div style="width:100%;"><span class="cornerBTM"><span class="corner4"></span><span class="corner3"></span>' +
	       '<span class="corner2"></span><span class="corner1"></span></span></div>';
	var searchhref;	
	
	if (selDivId == 'id_LIFE') {
		searchhref = "/goSubject?np=/subjectresults_ie6.ftl&pp=/subjectresults_ie6.ftl&maxLevels=3&maxSites=8&al=" + al + "&nodeID=67641";
		htmlstr += '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td width="33%" ' +
	          'align="center"><img src="/images/common/orange_arrow.gif" alt="" width="50" border="0" height="50"/>' +
	          '</td><td width="67%">&nbsp;</td></tr></table>';
		htmlstrbegin += '<div class="cs_21cBackground">' +
		      '<span class="cornerTOP"><span class="corner1"></span><span class="corner2"></span>' +
		      '<span class="corner3"></span><span class="corner4"></span></span>' +		   
		      '<div class="cs_cornerContent"><div class="cs_aligncenter">' +
              '<span class="cs_fontweight"><a id="id_lifeLink" href="' +searchhref+ '" class="twoonelink">Topics</a></span>' +
              '</div><br /><div>';		
	    contstr = '<div><h6 style="margin: 0em;">What are Life Skills?</h6>' +
	              '<div class="cs_commonSpace">' +
	              'Life Skills encompass a wide range of character traits that ' + 
	              'are valued both in personal relationships and in the workplace. ' + 
	              'Teachers have always taught &#8220;character skills&#8221; by ' + 
	              'example. The difference in teaching these as 21st century skills '+ 
	              'is in making them a deliberate part of lessons and helping ' +
	              'students see how the development of these character traits will serve them ' + 
	              'well in the world of work. ' +
	              '</div>' +  		     
	     	      '<div class="cs_hrdotgrey cs_commonSpace">&nbsp;</div>' +		    
		          '<h6 style="margin: 0em;">How do I Teach or Acquire Life Skills?</h6>' +
	              'Choose lessons that give opportunities for learners to demonstrate positive ' + 
	              'social interactions, to practice productive behaviors, or to show respect ' + 
	              'for the opinions of others.<br/> '+		    
	              '</div>';	
	} else if (selDivId == 'id_LEARN') {
		searchhref = "/goSubject?np=/subjectresults_ie6.ftl&pp=/subjectresults_ie6.ftl&maxLevels=3&maxSites=8&al=" + al + "&nodeID=67641";
		htmlstr += '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td width="33%">&nbsp;</td>' +
        '<td align="center"><img src="/images/common/orange_arrow.gif" alt="" width="50" border="0" height="50"/>' +
        '</td><td width="33%">&nbsp;</td></tr></table>';
		htmlstrbegin += '<div class="cs_21cBackground">' +
	      '<span class="cornerTOP"><span class="corner1"></span><span class="corner2"></span>' +
	      '<span class="corner3"></span><span class="corner4"></span></span>' +		   
	      '<div class="cs_cornerContent"><div class="cs_aligncenter">' +
          '<span class="cs_fontweight"><a id="id_learnLink" href="' +searchhref+ '"  class="twoonelink">Topics</a></span>' +
          '</div><br /><div>';	
		contstr = '<div><h6 style="margin: 0em;">What are Learning and Innovations Skills?</h6>' +
          '<div class="cs_commonSpace">' +
          'Learning and innovation skills are those skills which lifelong '+
          'learners have developed&#8212;the ability to think both critically '+
          'and creatively, to collaborate with others to create projects and '+
          'solve problems, and to communicate effectively both orally and in '+ 
          'writing.'+
          '</div>'+
		  '<div class="cs_hrdotgrey cs_commonSpace">&nbsp;</div> '+		    
		  '<h6 style="margin: 0em;">How do I Teach or Acquire Learning and '+ 
  		  'Innovations Skills?</h6> '+
		  'Critical thinking can be learned through puzzles and logic problems. '+
		  'Creativity can be encouraged through brainstorming and designing open-ended '+
		  'questions and projects where a &#8220;correct&#8221; answer is not expected. '+
		  'Communication skills can be developed through authentic speaking, writing, ' + 
		  'and publishing for real audiences.<br/>' +	    
		  '</div>';
		
	} else {
		searchhref = "/goSubject?np=/subjectresults_ie6.ftl&pp=/subjectresults_ie6.ftl&maxLevels=3&maxSites=8&al=" + al + "&nodeID=67641";
		htmlstr += '<table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td width="67%">&nbsp;</td>' +
        '<td align="center" width="33%"><img src="/images/common/orange_arrow.gif" alt="" width="50" border="0" height="50"/>' +
        '</td></tr></table>';
		htmlstrbegin += '<div class="cs_21cBackground">' +
	      '<span class="cornerTOP"><span class="corner1"></span><span class="corner2"></span>' +
	      '<span class="corner3"></span><span class="corner4"></span></span>' +		   
	      '<div class="cs_cornerContent"><div class="cs_aligncenter">' +
          '<span class="cs_fontweight"><a id="id_ictLink" href="' +searchhref+ '"  class="twoonelink">Topics</a></span>' +
          '</div><br /><div>';	
	    contstr = '<div><h6 style="margin: 0em;">What is ICT Literacy?</h6>' +
          '<div class="cs_commonSpace"> '+
          'Information and communications technology literacy (ICT), '+
          'also called digital literacy, is the ability to use technology '+ 
          'as a tool to acquire and demonstrate knowledge and skills. '+
          'Major areas of ICT literacy include information and media '+
          'literacies, knowing effective ways to find, synthesize, analyze, '+ 
          'and evaluate information from all types of media. '+
          '</div>'+
		  '<div class="cs_hrdotgrey cs_commonSpace">&nbsp;</div>'+
		  '<h6 style="margin: 0em;">How do I Teach or Acquire ICT Literacy?</h6>'+
		  'Choose lessons that encourage or require the use of various technologies to '+
		  'acquire information, to learn content, and/or to show mastery of content. '+
		  'Then assess both understanding of content and choice and use of technology.'+    
		  '</div>';
		
	}

	$('#'+ showDivId).html(htmlstr + htmlstrbegin + contstr + htmlstrclose);
	$('#'+ showDivId).css('visibility', 'visible');
	$('#'+ showDivId).css('height', '25.5em');

}

// shows error msg for ExcludeAcademicLevel preference if present
function fn_bodyContentError(acadlevel) {
    var acadlabel = '';
    if (acadlevel == 'E') {
      acadlabel = 'elementary';
    } else if (acadlevel == 'M') {
      acadlabel = 'middle';		        
    } else if (acadlevel == 'H') {
      acadlabel = 'high';		        
    } else {		         
    }
    $('#id_body').html('<br/><span class="cs_colorError cs_fontweight">Access to ' + acadlabel + ' school content has been blocked by your school.</span>');  
}

function saveUsers() {	
	var dimmer = new OverlayDimmer(document.body);
	dimmer.show();
	$.ajax({
		dataType: "json",
		type: "post",
		timeout: 30000,
		url: "/saveUser",
		async: false,
		data: getAjaxFormData("saveUser"),
		complete:function(response, status){
			if(status == "success") {
				jsonObject = $.parseJSON(response.responseText, true);
				var errorMsg = '';
			
				// If errors are available, then display the errors
				if(jsonObject.errors) {
					for(var i=0;i<jsonObject.errors.length; i++){
						if(jsonObject.errors[i] == '4'){
							errorMsg = 'Exceeded the allowed number of users on this school. So activating or locking a user is restricted.<br/>';
						}
					}				
				} else if(jsonObject.success) {
					errorMsg = 'Updated successfully.<br/>';
				}
				
				$("#saveUserMsg").html(errorMsg);
			}
		}  
	});	
	
	dimmer.hide();
	return false;
}


//validate the length of a field value
function verifyLength(field, length){
	var txt = jQuery.trim(field.value);
	if (txt.length > length){
		alert("Please limit your comment to " + length + " characters.")
		field.focus();
		return false;
	} else {
		return true;
	}
}
$(window).unbind('ajaxSend').bind('ajaxSend',function(event,request,settings){
	request.setRequestHeader('REQ-TYPE','AJAX');
});