<!-- //

// set global variables for browser detection and reference building
var isNav, isIE, isFX ;
var coll="";
var styleOb="";

if (parseInt(navigator.appVersion) >= 4) {
	if (navigator.appName == "Netscape") {
		isNav=true;
		if (navigator.vendor == "Firefox") {
			isFX=true;
			coll="all.";
			styleObj=".style";
		}
	} else {	
		isIE=true;
		coll="all.";
		styleObj=".style";
	}
}

//convert objectName String or object Reference
// into a valid object Reference
function getObject(obj) {
	var theObj ;
	if (typeof obj=="string") {
		theObj= eval("document." + coll + obj + styleObj) ;
	} else {
		theObj=obj ;
	}
	return theObj ;
}


//show a submenu
function showLayer(obj) {
	var theObj=getObject(obj);
	theObj.display='inline';
}

//hide a submenu
function hideLayer(obj) {
	var theObj=getObject(obj);
	theObj.display='none';
}



/***************************************************************************
*  Forms Validation functions
***************************************************************************/
// A utility function that returns true if a string contains only whitespace characters
function isblank(s) {
	for(var i=0; i<s.length; i++) {
		var c = s.charAt(i)
		if ((c!=' ') && (c!='\n') && (c!='\t')) {
			return false;
		}
	}
	return true;
}
			
// This is the function that performs forM verification. 
// It will be invoked from the onSubmit() event handler. The handler should return
// whatever value this function returns
function verify(f) {
	var msg;
	var empty_fields="";
	var errors="";
	var formValidationExpObj= new RegExp("_", "gi")
	
	// loop thru the elements of the form, looking for all text and textarea elements that dont 
	// have an "optional" property defined.. Then check for fields that are empty and make a list of them.
	// Also, if any of these elements have a "min" or "max" property defined, then verify that they are numbers
	// and that they are in the right range. Put together error messages for fields that re wrong.
	for (var i=0; i<f.length; i++) {
		var e=f.elements[i];
		
		if (((e.type=="text") || (e.type=="textarea") || (e.type=="select-one") || (e.type=="file") || (e.type=="checkbox"))  && (e.name.indexOf('tc_editable')==-1) && (!e.optional) ) {
			
			// first check if the field is empty
			if ((e.value==null) || (e.value=="") || isblank(e.value)) {
				empty_fields += "\n          " + e.name.replace(formValidationExpObj, " ");
				continue;
			}
			
			// Now check for fields that are supposed to be numeric
			if (e.numeric || (e.min!=null) || (e.max!=null)) {				
				var v=parseFloat(e.value);
				if ( isNaN(e.value) || ((e.min!=null) && (v < e.min)) ||  ((e.max!=null) && (v > e.max)) ) {
					errors+="- The field " + e.name + " must be a number";
					if (e.min!=null) errors += " that is greater than " + e.min;
					if (e.max!=null && e.min!=null) errors += " and less than " + e.max;
					else if (e.max!=null) errors += " that is less than " + e.max;
					errors+=".\n";
				}
			}
		}
	}
	
	// Now if there were any errors, then display the messages, and return false to prevent the form
	// from being submitted, otherwise return true
	if (!empty_fields && !errors) return true;
	
	msg="____________________________________________________________\n\n";
	msg+="The form was not submitted because of the following error(s)\n";
	msg+="Please correct the error(s) and re-submit the form\n";
	msg+="____________________________________________________________\n\n";
	//document.all.info.innerText=errors;
	if (empty_fields) {
		msg+="- The following required field(s) are empty:" + empty_fields + "\n";
		//if (errors) msg+="\n";
	}
	msg+=errors;
	alert(msg);
	return false;
}


// Functions that track the number of chars types into textarea fields
// Userd for dataTypes of 100 chars or more to avoid wide forms
function TrackCount(fieldObj,countFieldName,maxChars)
{
  var countField = eval("fieldObj.form."+countFieldName);
  var diff = maxChars - fieldObj.value.length;

  // Need to check & enforce limit here also in case user pastes data
  if (diff < 0)
  {
    fieldObj.value = fieldObj.value.substring(0,maxChars);
    diff = maxChars - fieldObj.value.length;
  }
 // countField.value = diff;
}

function LimitText(fieldObj,maxChars)
{
  var result = true;
  if (fieldObj.value.length >= maxChars)
    result = false;
  
  if (window.event)
    window.event.returnValue = result;
  return result;
}
  


//Function that can be called to quickly validate a field
function quickValidate(obj,val,type) {

	//takes types of: number
	
	switch (type) { 
		case 'number':
		if (isNaN(val) || val=='') { 
			alert("ERROR:...\n\nPlease select a number"); 
			obj.select() ; 
			return false;
		}
	}
}

//general purpose function to open a browser window
function openWin(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}

function toggleDisplay() {
	for (var i=0; i<toggleDisplay.arguments.length; i++) {
		
		var targetObj=eval('document.all.' + toggleDisplay.arguments[i]) ;
		var displaySetting=(targetObj.style.display)
		targetObj.style.display=(displaySetting=='none')?'inline':'none' ;
	}
}


/***************************************************************************
*  Struct datatype functions within forms
***************************************************************************/
function AddToStructure(objName, adminImgDirURL, structKeysArray) {
												
	// counter
	var Obj_Counter=structLengths[objName] ;
	var objContainer=eval('document.all.' + objName + '_overall_container') ;
	
	// remove function gets messy so create a variable for it
	var removeFunction="removeFromStructure('" + objName + "','"+ Obj_Counter + "')"
	
	// Insert the HTML
	if (structKeysArray.length > 0) {
		var optionsString=""
		for (i=0; i < structKeysArray.length; i++ ) {
			optionsString += '<option value="' + structKeysArray[i] + '">' + structKeysArray[i] + '</option>'
		
		}
		objContainer.insertAdjacentHTML('BeforeEnd', '<div id=' + objName + '_container_' + Obj_Counter + ' style=display:inline;><select name=' +objName + '_key_' + Obj_Counter + ' id=' +objName + '_key_' + Obj_Counter + ' class=TCinput>' + optionsString  + '</select> = <input name=' +objName + '_value_' + Obj_Counter + ' id=' +objName + '_value_' + Obj_Counter + ' value="" class=TCinput>&nbsp;<a onclick=' + removeFunction + '><img src=' + adminImgDirURL + '/delete.gif align=middle border=0 alt=delete onmouseover=this.style.cursor="hand"></a><br></div>')
	} else {
		objContainer.insertAdjacentHTML('BeforeEnd', '<div id=' + objName + '_container_' + Obj_Counter + ' style=display:inline;><input name=' +objName + '_key_' + Obj_Counter + ' id=' +objName + '_key_' + Obj_Counter + ' value="" class=TCinput> = <input name=' +objName + '_value_' + Obj_Counter + ' id=' +objName + '_value_' + Obj_Counter + ' value="" class=TCinput>&nbsp;<a onclick=' + removeFunction + '><img src=' + adminImgDirURL + '/delete.gif align=middle border=0 alt=delete onmouseover=this.style.cursor="hand"></a><br></div>')
	}
	//update the length of this structure
	structLengths[objName]++
}

function removeFromStructure(objName,line) {
	var objContainer=eval('document.all.' + objName + '_container_' + line)
	var objKey=eval('document.all.' + objName + '_key_' + line)
	var objValue=eval('document.all.' + objName + '_value_' + line)

	objKey.value=null
	objValue.value=null
	objContainer.style.display='None'

}

// 2 functions used for the creation of editable select boxes
function clipThis(f) {
	var oCombo=document.getElementById(f);   					// selected Box
	var oEditable=document.getElementById(f + 'tc_editable');  	// cliped text input field
	var clipTop=0;
	var clipRight=document.getElementById(f).offsetWidth;
	var clipBottom=document.getElementById(f).offsetHeight;
	var clipLeft=clipRight - 16; // show just he pulldown button
	//oCombo.style.clip="rect("+clipTop+"px "+clipRight+"px "+clipBottom+"px "+clipLeft+"px)";
	//oCombo.style.width=clipRight + "px";
	oEditable.style.width=clipLeft;
	oEditable.style.clientHeight=oCombo.style.height-2;
}

function addOption(f){
	
	var oCombo=document.getElementById(f);   					// selected Box
	var oEditable=document.getElementById(f + 'tc_editable');

	//First search for duplicates
	for(var i = 0; i < oCombo.options.length ; i++){
		//alert(oCombo.options[i].text + '=' + oEditable.value);
		if(oCombo.options[i].text == oEditable.value) { 
			oCombo.selectedIndex = i
			return;
		}
	}
	// Add new one
	oCombo.options[oCombo.options.length] = new Option(oEditable.value, oEditable.value);
	//Then select it
	oCombo.selectedIndex=oCombo.options.length-1	
}


// 2 functions used for the creation of editable select boxes
function clipThis_IE6(f) {
	var oCombo=eval('document.all.' + f);
	var oEditable=eval('document.all.' + f + 'tc_editable');
	var clipTop=0;
	var clipRight=document.getElementById(f).offsetWidth;
	var clipBottom=document.getElementById(f).offsetHeight;
	var clipLeft=clipRight - 18; // show just he pulldown button
	oCombo.style.clip="rect("+clipTop+"px "+clipRight+"px "+clipBottom+"px "+clipLeft+"px)";
	oCombo.style.width=clipRight + "px";
	oEditable.style.width=clipLeft;
	oEditable.style.height=document.getElementById(f).clientHeight;
}

function addOption_IE6(f){

	var oCombo=eval('document.all.' + f);
	var oEditable=eval('document.all.' + f + 'tc_editable');
	
	//if(oEditable.value != "") {
		//First search for duplicates
		for(var i = 0; i < oCombo.options.length ; i++){
			if(oCombo.options[i].text == oEditable.value)
				return;
		}
		// Add new one
		oCombo.options[oCombo.options.length] = new Option(oEditable.value, oEditable.value);
		//Then select it
		oCombo.selectedIndex=oCombo.options.length-1
		
		
	//}
}


// 2 functions for the TCCM editor for controlling and deleting items from the datagrid
function confirmDelete() {
					
	var confirmThis=false ;

	for(var i=0; i<document.editorForm.IDs.length; i++) {
		
		if (document.editorForm.IDs[i].checked) 
			confirmThis=true ; 
		}
	
		if (confirmThis) {
			if ( confirm('Are you sure you want to delete the item(s)...?') ) {
				document.editorForm.submit();  
			} 
		} else {
			alert("Please select and item to delete first...  ") ;
		}
}

function toggleAllIDs() {

	var turnOn=false
	
	for(var i=0; i<document.editorForm.IDs.length; i++) {
		if (!document.editorForm.IDs[i].checked) var turnOn=true ; }
	if (turnOn) {
		for(var i=0; i<document.editorForm.IDs.length; i++) { document.editorForm.IDs[i].checked=true ; }
	} else {
		for(var i=0; i<document.editorForm.IDs.length; i++) { document.editorForm.IDs[i].checked=false ; }
	}
}

// open new media Picker window

var newMediaPickerWin = '';				
function openMediaPicker(mediaPickerURL,controlID) {
	// if newMediaPickerWindow already oprn
	// pass over the controlID so that the right controller is updated with an image
	if (!newMediaPickerWin && newMediaPickerWin.location) {
		newMediaPickerWin.controlID=controlID ;
		newMediaPickerWin.focus();
		return false;
	} else {
		newMediaPickerWin=window.open(mediaPickerURL, 'mediaPickerWin', 'status=yes,toolbar=No,scrollbars=yes,location=No,directories=No,width=500,height=500,resizable=yes')
		if (!newMediaPickerWin.opener) newMediaPickerWin.opener = window;
	}
	//pass the focus over
	if (window.focus) {newMediaPickerWin.focus(); newMediaPickerWin.opener = self; }
	return true;
}

//function that previews media within the Editor
// also handles the links to view or edit the media
function updatePreview(img, rootMediaDirURL, tc_adminURL, imageDir, id) {

	if (!img) { return false };
	
	var mediaObj=eval("window.document.all." + img)
	var mediaValue='';
	
	if (!mediaObj.options) { return false };
							
	var mediaValue=mediaObj.options[mediaObj.selectedIndex].value;
	
	var mediaPrevObj=eval("document.all." + mediaObj.name + "preview")
	var mediaViewObj=eval("document.all." + mediaObj.name + "Viewer")
	var mediaEditObj=eval("document.all." + mediaObj.name + "Editor")
	var mediaEditorObj=eval("document.all." + mediaObj.name + "tc_editable")

	var isGIFREGEXObj=new RegExp(".*\.gif$", "gi")
	var isJPGREGEXObj=new RegExp(".*\.jpg$", "gi")
	var isHTMLREGEXObj=new RegExp(".*\.html$", "gi")
	var isTXTREGEXObj=new RegExp(".*\.txt$", "gi")
	var fixURLREGEX=new RegExp("[^\:]\/+", "gi")
	
	
	//Test to see if the selected Media is either gif or jpg
	var isGIF=isGIFREGEXObj.test(mediaValue)
	var isJPG=isJPGREGEXObj.test(mediaValue)
	var isHTML=isHTMLREGEXObj.test(mediaValue)
	var isTXT=isTXTREGEXObj.test(mediaValue)
					
	if (isGIF || isJPG) { var isImage=true
	} else { var isImage=false }
	
	if ((mediaValue == '') || (mediaValue == 'blank.gif' || mediaValue == false) || isImage == false) {				
		mediaPrevObj.src=tc_adminURL + '/tc_images/blank.gif';
		
		//write a link to view the non Image media
		if (mediaValue!="") {
			mediaViewObj.innerHTML='<a href="' + rootMediaDirURL + '/' + mediaValue + '" target="_blank"><img src="' + tc_adminURL + '/tc_images/view.gif" alt="View media" border="0" align="absmiddle"></a> '
		} else {
			mediaViewObj.innerHTML=''	
		}
	} else {
		if(mediaValue.substring(4,7)=="://") {
			mediaPrevObj.src=mediaValue;
		} else {
			mediaPrevObj.src=rootMediaDirURL + '/' + mediaValue;
			// fix the URL
			mediaPrevObj.src=mediaPrevObj.src.replace(/([^:])\/+/gi, "$1/");
		}
	}
	
	//write a link to edit HTML and TXT
	if (isHTML || isTXT) {
		mediaEditObj.innerHTML='<a href="' + tc_adminURL + '/tools/templates.cfm?OID=' + id + '&media=' + mediaValue + '" target="_blank"><img src="' + tc_adminURL + '/tc_images/edit.gif" alt="Edit media" border="0" align="absmiddle"></a> '
	}else {
		mediaEditObj.innerHTML=''
	}
	
	if(window.mediaEditorObj) {
		mediaEditorObj.value = mediaValue;
		mediaObj.focus()
	}
	
}

//function getAd(type, adsData) {

	// Type is the type of ad to dsiplay... Single, Multiple or Random
	// adsData is a reference to object of ads with AdName as keys

	//if (!window.previousAdsOnPage) { var previousAdsOnPage= new Array(#listQualify(REQUEST.previousAdsOnPage, "'")#) ; }
	//var adStr='' ;
	
	//if (type == 'Single') {
	//	for (thisAdName in adsData)  {
	//		adStr=adStr + '<!-- Insert Ad ' + adName + ' -->\n' ;
	//		adStr=adStr + eval(adsData[adName] + '\n' ;
	//		previousAdsOnPage[previousAdsOnPage.length]=adName ;
	//	}
	//}
//}

// -->


// Related articles picker functions

function viewArticle(object_id, instanceid){
	var id = "articles"+ "_" + instanceid ;
	var sel_box = document.getElementById(id);
	var article_id = sel_box.options[sel_box.selectedIndex].value;
	
	window.open("/tc_Admin/tools/editor.cfm?mode=edit&ID=" + article_id + "&OID=" + object_id);
}



function addArticle(object_id, article_type_id, item_id, instanceid){
	var id = "article_list_" + instanceid ;
	var selectBoxId = "articles_" + instanceid ;
	var sel_box = document.getElementById(selectBoxId);
	var article_id = sel_box.options[sel_box.selectedIndex].value;
	var http = getHTTPObject();
	http.open("GET", "/ext/mod/tcv22/tc_other_article.cfm?action=add&item_id=" + item_id  + "&object_id=" + object_id + "&article_type_id=" + article_type_id  + "&article_id=" + article_id + "&instanceid=" + instanceid, true);
	http.onreadystatechange = function(){
			if (http.readyState == 4){
				if(isNaN(http.responseText)) {
					alert(http.responseText) ;
				} else {
					var html = document.getElementById(id).innerHTML;
					var deleteAgs = object_id + ", " + item_id + ", " + article_type_id + ", " + article_id + ", \"" + instanceid + "\"" ; ;
					var updateArgs = object_id + ", " + item_id + ", " + article_type_id + ", " + article_id + ", \"" + instanceid + "\"" ;
					document.getElementById(id).innerHTML = html + "<span id='article_" + article_id + "_" + instanceid  + "'><a href='javascript:deleteArticle(" + deleteAgs + ")' style='text-decoration:none; font-weight:bold'>-</a> <input type='text' name='number_" + article_id + "_" + instanceid + "' id='number_" + article_id + "_" + instanceid + "' value='" + http.responseText.replace(/^\s+|\s+$/g, '') + "' style='width:30px' onChange='updateNumbers(" + updateArgs + ")' /> " + sel_box.options[sel_box.selectedIndex].text + "&nbsp;&nbsp;&nbsp;<br /></span>";
				}
			}
		}
	http.send(null);
}

function updateNumbers(object_id, item_id, article_type_id, article_id, instanceid){
	
	var num = document.getElementById("number_" + article_id + "_" + instanceid).value ;
	
	var http = getHTTPObject();
	http.open("GET", "/ext/mod/tcv22/tc_other_article.cfm?action=update&item_id=" + item_id  + "&object_id=" + object_id + "&article_type_id=" + article_type_id + "&article_id=" + article_id + "&instanceid=" + instanceid + "&number=" + num, true);
	http.onreadystatechange = function(){
			if (http.readyState == 4){
				if(http.responseText != 'OK') {
					alert(http.responseText);
				} else {
					alert("Updated Ordering");
				}
			}
		}
	http.send(null);
}

function deleteArticle(object_id, item_id, article_type_id, article_id, instanceid) {
	var id = "article_" + article_id + "_" + instanceid ;
	var http = getHTTPObject();
	http.open("GET", "/ext/mod/tcv22/tc_other_article.cfm?action=delete&item_id=" + item_id + "&object_id=" + object_id + "&article_type_id=" + article_type_id + "&article_id=" + article_id + "&instanceid=" + instanceid, true);
	http.onreadystatechange = function(){
		if (http.readyState == 4){
			var x = document.getElementById(id);
			x.parentNode.removeChild(x);
		}
	}
	http.send(null);
}




function logKey(object_id, item_id, article_id, e, instanceid){
	
	console.log(arguments) ;
	if(e.keyCode == 13){ /*If enter key is pressed*/
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;

		var article_id = targ.name.substr(targ.name.indexOf("_",0)+1);
		updateNumbers(object_id, item_id, article_id, instanceid);
		return false;
	} else {
		return true;
	}
}
function searchArticles(object_id, item_id, article_type_id, domainid, article_tablename, sqlcolumns, search_columns, orderby, instanceid){
	var id = "articles" + "_" + instanceid ;
	var selectBoxId = "select_box" + "_" + instanceid ;
	var http = getHTTPObject();
	var terms = document.getElementById("search_text" + "_" + instanceid).value;
	var casesensitive = document.getElementById("casesensitive_" + instanceid).checked;
	
	http.open("GET", "/ext/mod/tcv22/tc_other_article.cfm?action=search&item_id=" + item_id  + "&article_type_id=" + article_type_id  + "&domainid=" + domainid  + "&object_id=" + object_id + "&terms=" + terms + "&article_tablename=" + article_tablename + "&sqlcolumns=" + sqlcolumns + "&search_columns=" + search_columns + "&orderby=" + orderby + "&instanceid=" + instanceid + "&casesensitive=" + casesensitive, true);
	http.onreadystatechange = function(){
			if (http.readyState == 4){
				var select_html = '<select name="' + id + '" id="' + id + '">' + http.responseText + '</select>';
				var result_div = document.getElementById(selectBoxId);
				result_div.innerHTML = select_html;
			}
		}
	http.send(null);
}

