var timers = new Object();
var newWin1 = null;
//////////////////////////
//
//
////////////////////////
function addSelItem(fri_id)
{
	DDC_Content = document.Form1.elements["DDC_Contentadd" + fri_id].value;
	DDC_Order = document.Form1.elements["DDC_Orderadd" + fri_id].value;
	DDC_Default = document.Form1.elements["usedefadd" + fri_id].checked;
	
	if (DDC_Content != "")
		redirectMe("default.aspx?act=addddc&fri_id=" + fri_id + "&DDC_Content=" + escape(DDC_Content) + "&DDC_Order=" + DDC_Order + "&default=" + DDC_Default);
	else
		alert("You muse provide a value for this item.");
}

function editScheduledItem(id)
{
	redirectMe("default.aspx?act=scheduler&sch_id=" + id);
}

function delSelectBoxItem(ddc_id)
{
	if (confirm('Are you sure you want to delete this item?'))
		redirectMe("default.aspx?act=delddc&ddc_id=" + ddc_id);
}

function updateSelectBoxItem(fri_id, ddc_id)
{
	DDC_Content = document.Form1.elements['DDC_Content' + ddc_id].value;
	DDC_Order = document.Form1.elements['DDC_Order' + ddc_id].value;

	if (DDC_Content != "")
		redirectMe("default.aspx?act=updateddc&fri_id=" + fri_id + "&ddc_id=" + ddc_id + "&DDC_Content=" + DDC_Content + "&DDC_Order=" + DDC_Order + "&default=" + document.Form1.elements['usedef' + ddc_id].checked);
	else
		alert("You muse provide a value for this item.");
}

function delItem(fri_id)
{
	if(confirm('Are you sure you want to delete this question?'))
		redirectMe("default.aspx?act=delfri&fri_id=" + fri_id);
}

function changeFormType(fri_id, dat_id, currentDat)
{
	FRI_Caption = document.Form1.elements['_ctl0:CAPTION' + fri_id].value;
	FRI_Order = document.Form1.elements['FRI_Order' + fri_id].value;

	if (FRI_Caption != "" && FRI_Order != "")
		redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + dat_id + "&FRI_Caption=" + FRI_Caption + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=");
	else
		alert("You must provide a caption and an order.");
}

function updateItem(fri_id, currentDat)
{
	FRI_Caption = document.Form1.elements['_ctl0:CAPTION' + fri_id].value;
	FRI_Order = document.Form1.elements['FRI_Order' + fri_id].value;
	FRI_DefaultValue = "";
	
	if (currentDat == 1)
	{
		FRI_DefaultValue = document.Form1.elements['_ctl0:txt' + fri_id].value;
		redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + currentDat + "&FRI_Caption=" + escape(FRI_Caption) + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=" + escape(FRI_DefaultValue));
	}
	else if (currentDat == 2)
	{
		for (i = 0; i < document.Form1.elements['rad' + fri_id].length; i++)
		{
			if (document.Form1.elements['rad' + fri_id][i].checked)
				FRI_DefaultValue = document.Form1.elements['rad' + fri_id][i].value;	
		}
		redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + currentDat + "&FRI_Caption=" + escape(FRI_Caption) + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=" + escape(FRI_DefaultValue));
	}
	else if (currentDat == 3)
	{
		FRI_DefaultValue = document.Form1.elements['txtDate' + fri_id].value;

		if (_CF_checkdate(document.Form1.elements['txtDate' + fri_id].value))
			redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + currentDat + "&FRI_Caption=" + escape(FRI_Caption) + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=" + escape(FRI_DefaultValue));
		else if (FRI_DefaultValue == "")
			redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + currentDat + "&FRI_Caption=" + escape(FRI_Caption) + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=" + escape(FRI_DefaultValue));
		else
			alert("This field must be a date");
	}
	else if (currentDat == 4)
	{
		for(i = 0; i < document.Form1.elements.length; i++)
		{
			if (document.Form1.elements[i].type == "checkbox" && document.Form1.elements[i].name.substring(0, 6) == "usedef" && document.Form1.elements[i].name != "usedef")
				if (document.Form1.elements[i].checked)
				{
					m = document.Form1.elements[i].name.substring(6, document.Form1.elements[i].name.length);
					if (FRI_DefaultValue == "")
						FRI_DefaultValue = document.Form1.elements['DDC_Content' + m].value;
					else
						FRI_DefaultValue = FRI_DefaultValue + "," + document.Form1.elements['DDC_Content' + m].value;
				}
		}
		redirectMe("default.aspx?act=manageformtypechange&fri_id=" + fri_id + "&dat_id=" + currentDat + "&FRI_Caption=" + escape(FRI_Caption) + "&FRI_Order=" + FRI_Order + "&FRI_DefaultValue=" + escape(FRI_DefaultValue));
	}
}
/////////////////////////
//
//
///////////////////////
function HelpWindow()
{
	if (!newWin1 || newWin1.closed) {
		newWin1 = window.open("help_file.aspx", "newWin1", "resizable=no,scrollbars=yes,width=500,height=240,toolbar=no")
	}
	else
	{
		newWin1.focus();
	}
}

function CloseHelpWindow()
{
	if(newWin1){
		newWin1.close();
	}
}
		
function DoLayer(id)
{
	menu = eval(id + 'div');
	pos = eval(id + 'pos');
	menu.style.left = pos.offsetLeft + 45 - menu.offsetWidth;
	menu.style.top = pos.offsetTop + pos.offsetHeight - 2;
	menu.style.visibility = "visible";
	re = new RegExp("date");
	if (id.match(re) != "date")
	{
		hideMyElement('SELECT', menu);
		hideMyElement('OBJECT', menu);
	}
	layerover(id);
}
	
function layerover(id)
{
	if(timers[id + 'timerRunning'])      
		clearInterval(timers[id + 'timerID']);
	timers[id + 'timerRunning'] = false;
}
	
function starttimer(id)
{
	timers[id + 'timerID'] = setInterval("HideIt('" + id + "')",50);
	timers[id + 'timerRunning'] = true;
}

function HideIt(id)
{
	menu = eval(id + 'div');
	menu.style.visibility = "hidden";
	if(timers[id + 'timerRunning'])      
		clearInterval(timers[id + 'timerID']);
	showMyElement("SELECT");
	showMyElement("OBJECT");
}

function hideMyElement(elmID, mnu)
{
	if (document.all)
	{
		for (i = 0; i < document.all.tags(elmID).length; i++)
		{
			obj = document.all.tags(elmID)[i];
			if (! obj || ! obj.offsetParent)
				continue;

			// Find the element's offsetTop and offsetLeft relative to the BODY tag.
			objLeft   = obj.offsetLeft;
			objTop    = obj.offsetTop;
			objParent = obj.offsetParent;
			while (objParent.tagName.toUpperCase() != "BODY")
			{
				objLeft  += objParent.offsetLeft;
				objTop   += objParent.offsetTop;
				objParent = objParent.offsetParent;
			}
			// Adjust the element's offsetTop relative to the dropdown menu
			x  = window.event.srcElement.offsetLeft + window.event.srcElement.offsetParent.offsetLeft;
			objTop = objTop - mnu.style.top;

			if (x > (objLeft + obj.offsetWidth) || objLeft > (x + mnu.offsetWidth));
			else if (objTop > mnu.offsetHeight);
			else obj.style.visibility = "hidden";
		}
	}
}

function showMyElement(elmID)
{
	if (document.all)
	{
		for (i = 0; i < document.all.tags(elmID).length; i++)
		{
			obj = document.all.tags(elmID)[i];
			if (! obj || ! obj.offsetParent)
				continue;
			obj.style.visibility = "";
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////
//																						//
// Article Functions																	//
//																						//
//////////////////////////////////////////////////////////////////////////////////////////

function MoveArticleUp(nlrid, artid, order, pos)
{
	redirectMe("default.aspx?act=movearticleup&nlr_id=" + nlrid + "&art_id=" + artid + "&art_order=" + order + "&art_position=" + pos);
}

function MoveArticleDown(nlrid, artid, order, pos)
{
	redirectMe("default.aspx?act=movearticledown&nlr_id=" + nlrid + "&art_id=" + artid + "&art_order=" + order + "&art_position=" + pos);
}

function EditArticle(nlrid, artid, bit2Col, temp)
{
	redirectMe("default.aspx?act=editarticle&nlr_id=" + nlrid + "&art_id=" + artid + "&has2columns=" + bit2Col + "&template=" + temp);
}

function EditPoll(nlrid, artid, poll)
{
	redirectMe("default.aspx?act=editpoll&nlr_id=" + nlrid + "&art_id=" + artid + "&epl_id=" + poll);
}

function DeletePoll(nlrid, artid, poll)
{
	if (confirm('Are you sure you want to delete this poll?'))
		redirectMe("default.aspx?act=delpoll&nlr_id=" + nlrid + "&art_id=" + artid + "&epl_id=" + poll);
}

function DeleteArticle(nlrid, artid)
{
	if (confirm('Are you sure you want to delete this article?'))
		redirectMe("default.aspx?act=deletearticle&nlr_id=" + nlrid + "&art_id=" + artid);
}

function ChangePosition(nlrid, artid, pos)
{
	redirectMe("default.aspx?act=changeposition&nlr_id=" + nlrid + "&art_id=" + artid + "&art_position=" + pos);
}

function AddArticle(artid, nlrid)
{
	redirectMe("default.aspx?act=duplicatearticle&nlr_id=" + nlrid + "&art_id=" + artid);
}

function CopyArticle(title, artid, nlrid)
{
	var newname=prompt('Please enter a name for this article:', title);
	if ((newname==' ') || (newname==null))
		alert("Invalid name, please try again.");
	else
		redirectMe("default.aspx?act=duplicatearticle&nlr_id=" + nlrid + "&art_id=" + artid + "&art_title=" + escape(newname));	
}


//////////////////////////////////////////////////////////////////////////////////////////
//																						//
// List Functions																		//
//																						//
//////////////////////////////////////////////////////////////////////////////////////////

function renameList(lstID, lstname)
{
	redirectMe("default.aspx?act=renamelist&lst_id=" + lstID + "&lst_name=" + lstname);
}

function deleteList(lstID, delStr)
{
	if (confirm(delStr))
		redirectMe("default.aspx?act=deletelist&lst_id=" + lstID);
}

//////////////////////////////////////////////////////////////////////////////////////////
//																						//
// Newsletter List Functions															//
//																						//
//////////////////////////////////////////////////////////////////////////////////////////

function openMePending(nlrid)
{
	if (confirm('Please note, you cannot modify a pending newsletter unless you cancel it and reschedule it.'))
		redirectMe("default.aspx?act=Newsletterbuild&nlr_id=" + nlrid);
}

function openMe(nlrid)
{
	redirectMe("default.aspx?act=Newsletterbuild&nlr_id=" + nlrid);
}

function sendMe(nlrid)
{
	if (confirm('Are you sure you want to send this Newsletter?'))
		redirectMe("default.aspx?act=Newsletterbuild&nlr_id=" + nlrid);
}

function cancelMe(nlrid)
{
	redirectMe("default.aspx?act=Newsletterbuild&nlr_id=" + nlrid);
}

function reportMe(nlrid)
{
	redirectMe("default.aspx?act=report&nlr_id=" + nlrid);
}

function copyMe(nlrid)
{
	showPopWin('copy.html?nlrid=' + nlrid, 250, 120, null);
	/*var newname=prompt('Please enter a name for this copy:', ' ');
	if ((newname==' ') || (newname==null))
		alert("Invalid name, please try again.");
	else
		redirectMe("default.aspx?act=copynlr&nlr_id=" + nlrid + "&nlrname=" + escape(newname));*/
}

function delMe(nlrid)
{
	if (confirm('Are you sure you want to delete this Newsletter?'))
		redirectMe("default.aspx?act=deleteNewsletter&nlr_id=" + nlrid);
}

function cancelSend(nlrid, time)
{
	if (confirm('Are you sure you want to cancel this Newsletter from sending on ' + time.split(" ")[0] + " at " + replaceSubstring(time, time.split(" ")[0], "") + '?'))
		redirectMe("default.aspx?act=canschnlr&nlr_id=" + nlrid + "&time=" + escape(time));
}

function delSend(nlrid, time)
{
	if (confirm('Are you sure you want to delete this Newsletter and cancel it from sending on ' + time.split(" ")[0] + " at " + replaceSubstring(time, time.split(" ")[0], "") + '?'))
		redirectMe("default.aspx?act=delschnlr&nlr_id=" + nlrid + "&time=" + escape(time));
}

function redirectMe(url)
{
	addField(document.forms[0], 'hidden', 'reloadaction', url);
	document.forms[0].submit();
}

function addField(form, fieldType, fieldName, fieldValue)
{
	var input = document.createElement('INPUT');

	input.type = fieldType;
	input.name = fieldName;
	input.value = fieldValue;
	
	form.appendChild(input);
}

function previewImage(height, width, content)
{
	previewWindow = window.open("","sub","status,scrollbars=yes,resize=true");
	if(!previewWindow.opener)
		previewWindow.opener = window;

	writeToWindow(content);
	previewWindow.focus();
}

function writeToWindow(wincontent) {
	content = "<html><body bgcolor=white leftmargin=0 topmargin=0 offset=0 marginheight=0 marginwidth=0><div align=center>"
	content = content + wincontent
	content = content + "<br><a href=javascript:close()>Close Window</a></div><br></body></html>"
	previewWindow.document.write(content)
	previewWindow.document.close()
}

function deleteImage(img, fldr)
{
	if (confirm('Are you sure you want delete this image?'))
	{
		if (fldr != "")
			document.location.href = "deleteimage.aspx?fldr=" + escape(fldr) + "&img=" + img;
		else
			document.location.href = "deleteimage.aspx?img=" + img;
	}
}

function imabeBrowser()
{
	imageBrowser= window.open("imagebrowser.aspx","Imabe_Browser","status,width=650,scrollbars=yes,resize=true");
	if(!imageBrowser.opener)
		imageBrowser.opener = window;
	imageBrowser.focus();
}

function SelectImage(imgTxt, srcTxt)
{
	opener.document.Form1.elements['_ctl0:txtImage'].value = imgTxt;
	img = opener.document.getElementById('_ctl0_imgImage');
	img.src = srcTxt;
	window.close();
}


var calWin1 = null;

function CalendarWindow(id){
	if (!calWin1 || calWin1.closed) {
		calWin1 = window.open("calendar.aspx?opener=true&formname=Form1.elements['txtDate" + id + "']", "calWin1", "resizable=no,scrollbars=no,width=158,height=193,toolbar=no")
	}else{
		calWin1.focus();
	}
}

function CalendarWindow2(id){
	if (!calWin1 || calWin1.closed) {
		calWin1 = window.open("calendar.aspx?opener=true&formname=Form1.elements['QQ" + id + "']", "calWin1", "resizable=no,scrollbars=no,width=158,height=193,toolbar=no")
	}else{
		calWin1.focus();
	}
}

function _CF_checkdate(object_value)
    {
    //Returns true if value is a date format or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a date in the mm/dd/yyyy format
	isplit = object_value.indexOf('/');

	if (isplit == -1 || isplit == object_value.length)
		return false;

    sMonth = object_value.substring(0, isplit);

	if (sMonth.length == 0)
        return false;

	isplit = object_value.indexOf('/', isplit + 1);

	if (isplit == -1 || (isplit + 1 ) == object_value.length)
		return false;

    sDay = object_value.substring((sMonth.length + 1), isplit);

	if (sDay.length == 0)
        return false;

	sYear = object_value.substring(isplit + 1);

	if (!_CF_checkinteger(sMonth)) //check month
		return false;
	else
	if (!_CF_checkrange(sMonth, 1, 12)) //check month
		return false;
	else
	if (!_CF_checkinteger(sYear)) //check year
		return false;
	else
	if (!_CF_checkrange(sYear, 0, 9999)) //check year
		return false;
	else
	if (!_CF_checkinteger(sDay)) //check day
		return false;
	else
	if (!_CF_checkday(sYear, sMonth, sDay)) // check day
		return false;
	else
		return true;
    }

function _CF_checkday(checkYear, checkMonth, checkDay)
    {

	maxDay = 31;

	if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
	if (checkMonth == 2)
	{
		if (checkYear % 4 > 0)
			maxDay =28;
		else
		if (checkYear % 100 == 0 && checkYear % 400 > 0)
			maxDay = 28;
		else
			maxDay = 29;
	}

	return _CF_checkrange(checkDay, 1, maxDay); //check day
    }



function _CF_checkinteger(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is an integer defined as
    //   having an optional leading + or -.
    //   otherwise containing only the characters 0-9.
	var decimal_format = ".";
	var check_char;

    //The first character can be + -  blank or a digit.
	check_char = object_value.indexOf(decimal_format)
    //Was it a decimal?
    if (check_char < 1)
	return _CF_checknumber(object_value);
    else
	return false;
    }



function _CF_numberrange(object_value, min_value, max_value)
    {
    // check minimum
    if (min_value != null)
	{
        if (object_value < min_value)
		return false;
	}

    // check maximum
    if (max_value != null)
	{
	if (object_value > max_value)
		return false;
	}
	
    //All tests passed, so...
    return true;
    }



function _CF_checknumber(object_value)
    {
    //Returns true if value is a number or is NULL
    //otherwise returns false	

    if (object_value.length == 0)
        return true;

    //Returns true if value is a number defined as
    //   having an optional leading + or -.
    //   having at most 1 decimal point.
    //   otherwise containing only the characters 0-9.
	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;

    //The first character can be + - .  blank or a digit.
	check_char = start_format.indexOf(object_value.charAt(0))
    //Was it a decimal?
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1)
		return false;
        
	//Remaining characters can be only . or a digit, but only one decimal.
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0)
			return false;
		else if (check_char == 1)
		{
			if (decimal)		// Second decimal.
				return false;
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
        // ignore leading blanks

		}
	        else if (trailing_blank)
			return false;
		else
			digits = true;
	}	
    //All tests passed, so...
    return true
    }



function _CF_checkrange(object_value, min_value, max_value)
    {
    //if value is in range then return true else return false

    if (object_value.length == 0)
        return true;


    if (!_CF_checknumber(object_value))
	{
	return false;
	}
    else
	{
	return (_CF_numberrange((eval(object_value)), min_value, max_value));
	}
	
    //All tests passed, so...
    return true;
    }



function LogOut()
{
	showPopWin('logout.html', 250, 100, null);
}

function LogOutCSV()
{
	if (confirm("Are you sure you want to log out?"))
		top.location.href = "logout.aspx";
}

function insertNodeAtSelection(windowObject, insertNode)
{
    var selection = windowObject.getSelection();
    var range = selection.getRangeAt(0);
    selection.removeAllRanges();
 
    range.deleteContents();
 
    var container = range.startContainer;
    var startPosition = range.startOffset;
 
    range = document.createRange();
 
    if ((container.nodeType == 3) && (insertNode.nodeType == 3))
    {
        container.insertData(startPosition, insertNode.nodeValue);
        range.setEnd(container, startPosition + insertNode.length);
        range.setStart(container, startPosition + insertNode.length);
    }
    else
    {
        var afterNode;
        if (container.nodeType == 3)
        {
            var textNode = container;
            container = textNode.parentNode;
            var nodeText = textNode.nodeValue;
 
            var textBefore = nodeText.substr(0, startPosition);
            var textAfter = nodeText.substr(startPosition);
 
            var beforeNode = document.createTextNode(textBefore);
            var afterNode = document.createTextNode(textAfter);
 
            container.insertBefore(afterNode, textNode);
            container.insertBefore(insertNode, afterNode);
            try
            {
                container.insertBefore(beforeNode, insertNode);
            }
            catch (exc) {}
 
            container.removeChild(textNode);
        }
        else
        {
            afterNode = container.childNodes[startPosition];
            container.insertBefore(insertNode, afterNode);
        }
        try
        {
            range.setEnd(afterNode, 0);
            range.setStart(afterNode, 0);
        }
        catch (exc) {}
    }
    try
    {
        selection.addRange(range);
    }
    catch (exc) {}
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

function CreateNewFolder(fldr)
{
	var newname=prompt('Please enter a folder name:', ' ');
	if ((newname==' ') || (newname==null) || (newname=='thumbs') || (newname=='_vt_cnf'))
		alert("Invalid name, please try again.");
	else
	{
		if (fldr != "")
			document.location.href = "/imagebrowser.aspx?act=createFolder&fldr=" + fldr + "&newfldr=" + escape(newname);
		else
			document.location.href = "/imagebrowser.aspx?act=createFolder&newfldr=" + escape(newname);
	}
}

function deleteFolder(fldr, parent)
{
	if (confirm('Are you sure you want to delete this folder?'))
	{
		if (parent != "")
			document.location.href = "/imagebrowser.aspx?act=deleteFolder&fldr=" + parent + "&newfldr=" + escape(fldr);
		else
			document.location.href = "/imagebrowser.aspx?act=deleteFolder&newfldr=" + escape(fldr);
	}
}
