var isIE = (navigator.appName == 'Microsoft Internet Explorer');
var visibleDivState = 'block';
var hiddenDivState = 'none';
if (!isIE)
{
	visibleDivState = 'table-row';
//	hiddenDivState = 'hidden';
}


function postForm(url) 
{
    saveRichTextEditors();
    var formObject = document.getElementById("MainForm");
    formObject.action = url;
    formObject.submit();
}

function submitForm(link, queryValue) 
{
    saveRichTextEditors();
    var formObject = document.getElementById("MainForm");
    formObject.linkValue.value = link;
    if (queryValue != null)
        formObject.action = "?" + queryValue;
    formObject.submit();
}

function _(link)
{
	submitForm(link);
}

function uploadFile(link)
{
	
	/*MainForm.linkValue.value = link;
	chrome = "height=140,width=500,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no";
	uniqueID = (new Date()).getTime() % 1000000000;
	window.open("uploadprogress.aspx?ProgressID=" + uniqueID, uniqueID, chrome);
	MainForm.action = "default.aspx?UploadID=" + uniqueID;
	submitForm("DMSUploadFile", 0, "", true);*/
}

function GetClientUTC()
{    
    var now = new Date();
    var offset = now.getTimezoneOffset();
    document.Form1.hdClientUTC.value = offset;
}

var richTextFieldName = "";
function popupRichText(name, divName, maxLength)
{
	richTextFieldName = name;
	var value = document.forms[0].elements[name].value;
	openWindow("RichText.aspx?ID=" + name + "&divName=" + divName + "&Count=" + maxLength + "&Text=" + value, "TextEditor", "height=500,width=600,channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=0,status=0,toolbar=0")
}

function openWindow(sURL, sWindowName, sAttributes)
{
	var newWindow =window.open(sURL, sWindowName, sAttributes);
	newWindow.focus();
}

function setFocus(controlName)
{
	try
	{
		var control = document.getElementById(controlName);
		if (control != null)
		{
			control.focus();
//			control.select();
		}
	}
	catch(e){}
}

function toggleRadio(name, selectedIndex, value)
{
	//If the radio button had a link as the value, thenn redirect to there
	if (value.toUpperCase().substr(0, 4) == "HTTP")
		document.location.href = value;
		
	index=0;
	checkBoxImage = document.getElementById(name + index);
	while(checkBoxImage != null)
	{
	    checkBoxImage.src = virtualRoot + 'images/radiooff.png';
		index++;
		checkBoxImage = document.getElementById(name + index);
	}
	checkBoxImage = document.getElementById(name + selectedIndex);
	checkBoxImage.src = virtualRoot + 'images/radioon.png';
	hiddenField = document.getElementById(name);
	hiddenField.value = value;
	//AccountRenderer_ViewExtension_StoreRenderer_ViewObject_DynamicForm_Feature11
//	alert(hiddenField.id + '=' + hiddenField.value);
}

function toggleCheckBox(name, value, on)
{
	var index = 0;
	var checkBoxImage = document.getElementById(name + value);
	var hiddenField = document.getElementById(name);
	var intValue = parseInt(hiddenField.value);
	if (on != null)
	{
		//Trying to set the value manually - reverse what we want so that it will get toggled
		if (on)
		{
			//Subtract it if necessary/turn it off
			if ((intValue & value) > 0)
				intValue = intValue - value;
		}
		else
			if ((intValue & value) == 0)
				intValue = intValue + value; //Turn it on so it will get turned off
	}
	if ((intValue & value) > 0)
	{
		checkBoxImage.src = virtualRoot + 'images/checkboxoff.png';
		intValue = intValue - value;
	}
	else
	{
		checkBoxImage.src = virtualRoot + 'images/checkboxon.png';
		intValue = intValue + value;
	}
	hiddenField.value = intValue;
}

function spinUp(textBoxName, values, wrap){spin(textBoxName, values, 1, wrap);}
function spinDown(textBoxName, values, wrap){spin(textBoxName, values, -1, wrap);}
var spinBusy = false;
function spin(textBoxName, values, direction, wrap)
{
    if (!spinBusy)
    {
        spinBusy = true;
	    var list = values.split('|');
	    var textBox = document.getElementById(textBoxName);
	    var value = textBox.value;
	    //Find the current entry
	    for(var index=0;index<list.length;index++)
		    if (list[index] == value)
			    break;
	    if (index == list.length) //Didn't find a match, show the first or last one
	    {
		    if (direction == -1)
		    {
			    index = 0; //Down - show the first
		    }
		    else
			    index = list.length - 1; //Up - show the last
	    }
	    else
		    index = index + direction; //Move the index appropriately
	    if (index < 0)
		    if (wrap)
		    {
			    index = list.length - 1; //Wrap around to the top
		    }
		    else
			    index = 0; //Stay at the bottom
	    if (index >= list.length)
		    if (wrap)
		    {
			    index = 0; //Wrap around to the bottom
		    }
		    else
			    index = list.length - 1; //Stay at the top
	    if ((index > -1) && (index < list.length))
	    {
		    textBox.value = list[index];
	    }
	    else
		    textBox.value = ""; //If something went wrong, blank the value out
	    spinBusy = false;
	}
}

function checkUploadFields(fieldList, link)
{
	var fields = fieldList.split(';');
	var isUploadFile = false;
	for(var index=0;index<fields.length;index++)
	{
		var name = fields[index];
		if (name.length > 0)
		{
			var control = document.getElementById(name);
			if (control != null)
				if (control.value.length > 0)
				{
					isUploadFile = true;
					break;
				}
		}
	}
	if (isUploadFile)
	{
		var divControl = document.getElementById("fileUploadDiv");
		var iframeControl = document.getElementById("fileUploadIFrame");
		if ((divControl != null) && (iframeControl != null))
		{
			var uniqueID = (new Date()).getTime() % 1000000000;
			divControl.style.display = visibleDivState;
			iframeControl.src = virtualRoot + "miniuploadprogress.aspx?ProgressID=" + uniqueID;
		}
	}
	submitForm(link);
}

function cd(name, link)
{
	if (confirm("Are you sure you wish to delete \"" + name + "\"?"))
		document.location.href = link;
}

function cds(name, link) {
    if (confirm("Are you sure you wish to delete \"" + name + "\"?"))
        submitForm(link);
}

function cr(name, link)
{
	if (confirm("Are you sure you wish to remove \"" + name + "\"?"))
		document.location.href = link;
}

function crs(name, link) {
    if (confirm("Are you sure you wish to remove \"" + name + "\"?"))
        submitForm(link);
}

function cc(name, link)
{
    newname = "";
    done = false;
    while (!done)
    {
        newname = name.replace(/&339;/g,"\"");
        if (newname != name)
            name = newname;
        else
            done = true;
    }
	if (confirm(name))
		document.location.href = link;
}

function ccs(name, link) {
    newname = "";
    done = false;
    while (!done) {
        newname = name.replace(/&339;/g, "\"");
        if (newname != name)
            name = newname;
        else
            done = true;
    }
    if (confirm(name))
        submitForm(link);
}

function goToURL(url)
{
	document.location.href = url;
}

function toggleDivDirect(id)
{
    div = document.getElementById(id);
    if (div != null) 
    {
        if (div.style.display == hiddenDivState) 
        {
            div.style.display = visibleDivState;
        }
        else
            div.style.display = hiddenDivState;
    }
}

// Used by UIControls.CollapsibleMenu
// Added by Jamie Smith 
function ShowHideDiv(id)
{
	div = document.getElementById(id);
	image = document.getElementById(id + "_image");
	if (div.style.display == "none")
	{
		div.style.display = "block";
		image.src = image.src.replace(/right/,"down");
		
	}
	else
	{
		div.style.display = "none";
		image.src = image.src.replace(/down/,"right");
	}
}

function toggleDiv(id)
{
	abstractDiv = document.getElementById('abstractDiv' + id);
	bodyDiv = document.getElementById('bodyDiv' + id);
	if (abstractDiv.style.display == hiddenDivState)
	{
		abstractDiv.style.display = visibleDivState;
		bodyDiv.style.display = hiddenDivState;
	}
	else
	{
		abstractDiv.style.display = hiddenDivState;
		bodyDiv.style.display = visibleDivState;
	}
}

function setDiv(id, isVisible)
{
	div = document.getElementById(id);
	if (div)
	{
		if (isVisible)
		{
			div.style.display = visibleDivState;
		}
		else
			div.style.display = hiddenDivState;
	}
}

function toggleLayers(layer1, layer2)
{
	layer1Object = document.getElementById(layer1);
	layer2Object = document.getElementById(layer2);
	if (layer1Object.style.display == hiddenDivState)
	{
		layer1Object.style.display = visibleDivState;
		layer2Object.style.display = hiddenDivState;
	}
	else
	{
		layer1Object.style.display = hiddenDivState;
		layer2Object.style.display = visibleDivState;
	}
}

function valueToMonthYear(controlName)
{
	var control = document.getElementById('" + controlName + "Date');
	alert(1);
	var values = control.value.split('/');
	alert(control.value, values.length);
	return values[0] + '/' + values[2];
}

function valueToMonthDayYear(controlName)
{
	var control = document.getElementById('" + controlName + "Date');
	return control.value;
}

function hoverMenu(target, menuName, on)
{
    var className = 'MenuTopTableNormal';
    if (on)
        className = 'MenuTopTableHover';
    target.className = className;
    var popupMenu = document.getElementById(menuName + 'Popup');
    //alert(popupMenu + ':' + menuName + 'Popup');
    if (popupMenu)
    {
        if (on)
        {
            popupMenu.style.display = visibleDivState;
        }
        else
            popupMenu.style.display = hiddenDivState;
    }
}

function hideTextboxLabel(textBox)
{
	if (textBox.value == textBox.label)
		textBox.value = '';
}

function showTextboxLabel(textBox)
{
	if (textBox.value.length == 0)
		textBox.value = textBox.label;
}

//****************Multi-select move functions
// Compare two options within a list by TEXT
function compareOptionText(a, b) 
{ 
//  var sA = parseInt(a.text, 36);  
//  var sB = parseInt(b.text, 36);  
//  return sA - sB;
	return a.text.compareTo(b.text);
}

// Dual list move function
function moveDualList(hiddenName, selectedName, fromListName, toListName, moveAll) 
{
	var fromList = document.getElementById(fromListName);
	var toList = document.getElementById(toListName);
//alert(fromList.name + "->" + toList.name + ":" + fromList.selectedIndex);

	// Do nothing if nothing is selected
	if ((fromList.selectedIndex == -1) && (moveAll == false))
		return;
	            
	//Add existing items in the toList to our temp array
	newToList = new Array(toList.options.length);
	var length = 0;
	for(length = 0; length < toList.options.length; length++) 
	{
		if (toList.options[length] != null)
		  newToList[length] = new Option(toList.options[length].text, toList.options[length].value);//, toList.options[length].defaultSelected, toList.options[length].selected);
	}

	//Add all selected items from the from list to our temp array
	for(var index = 0; index < fromList.options.length; index++) 
	{ 
		if (fromList.options[index] != null && (fromList.options[index].selected == true || moveAll))
		{
		   newToList[length] = new Option(fromList.options[index].text, fromList.options[index].value);// fromList.options[index].defaultSelected, fromList.options[index].selected);
		   length++;
		}
	}
  
	// Sort the temp array
	//newToList.sort(compareOptionText);

	// Populate the to list with the items from the temp array
	for (var index = 0; index < newToList.length; index++) 
	{
		if (newToList[index] != null)
		  toList.options[index] = newToList[index];
	}

	// Erase the selected elements from the from list
	for(var index = fromList.options.length - 1; index >= 0; index--) 
	{ 
		if (fromList.options[index] != null && (fromList.options[index].selected == true || moveAll))
		   fromList.options[index] = null;
	}
	
	//Update the hidden field
	var hiddenValue = document.getElementById(hiddenName);
	var selectedList = document.getElementById(selectedName);
	hiddenValue.value = '';
	for(var index = 0; index < selectedList.options.length; index++) 
	{ 
		if (hiddenValue.value.length > 0)
			hiddenValue.value += "|";
		hiddenValue.value += selectedList.options[index].value;
	}
}

function hideTextboxLabel(textBox)
{
	if (textBox.value == textBox.label)
		textBox.value = '';
}

function showTextboxLabel(textBox)
{
	if (textBox.value.length == 0)
		textBox.value = textBox.label;
}

function checkCharacterCount(control, maxLength)
{
	var charsLeft = maxLength - control.value.length;
	if (charsLeft < 0)
	{
		control.value = control.value.substr(0, maxLength);
		charsLeft = 0;
	}
	var div = document.getElementById(control.id + 'CharacterCount');
	if (div != null)
		div.innerHTML = charsLeft.toString();
}

var lastTypeTextBox = '';

function typeTextBoxValue(textBoxName, value)
{
	var textBox = document.getElementById(textBoxName);
	if (textBox != null)
	{
		if (lastTypeTextBox != textBoxName)
		{
			textBox.value = '';
			lastTypeTextBox = textBoxName;
		}
		textBox.value += value;
	}
}

function deleteTextBoxValue(textBoxName, value)
{
	var textBox = document.getElementById(textBoxName);
	if (textBox != null)
	{
		lastTypeTextBox = textBoxName;
		textBox.value = textBox.value.substr(0, textBox.value.length - 1);
	}
}

function updateControlGroup(controlName, possibleValues, groupName, andValue, reverseLogic)
{

     //"AccountRenderer_ViewExtension_StoreRenderer_Billing_DynamicForm_PaymentType"
     //"1,2,3,4,5"
     //"FDOFHKTTPH"
     //false
     //true
	control = document.getElementById(controlName);
    //alert(controlName + ":" + possibleValues + ":" + groupName + ":" + control.value);

	//Walk all possible values and set the corresponding controls according to the visibility
	var values = possibleValues.split(',');
	for(valueIndex=0;valueIndex<values.length;valueIndex++)
	{
		var currentValue = values[valueIndex]; //1, then 2, then 3
		if (currentValue.length > 0)
		{
			var visible = (control.value == currentValue);
			if (andValue)
				visible = ((parseInt(control.value)  & parseInt(currentValue) ) > 0);
			if (reverseLogic)
				visible = !visible;
			var index = 0;
			//Toggle the ones that match the given value
			while (true) {
			    var divName = groupName + currentValue + index;
			    //alert(divName + 'Content' + ":" + document.getElementById(divName + 'Content'));
			    if (!document.getElementById(divName + 'Content'))
			        break;
			    setDiv(divName + 'StartSpace', visible);
			    setDiv(divName + 'Content', visible);
			    setDiv(divName + 'Comment', visible);
			    setDiv(divName + 'EndSpace', visible);
			    index++;
			}
            //try toggling the reverse of that - that is signified by an underscore before a value
			var index = 0;
			while (true) {
			    var divName = groupName + '_' + currentValue + index;
			    //alert(divName + 'Content' + ":" + document.getElementById(divName + 'Content'));
			    if (!document.getElementById(divName + 'Content'))
			        break;
			    setDiv(divName + 'StartSpace', !visible);
			    setDiv(divName + 'Content', !visible);
			    setDiv(divName + 'Comment', !visible);
			    setDiv(divName + 'EndSpace', !visible);
			    index++;
			}
}
	}
}

var nicEditInstance = null;
function toggleRichTextEditor(Name)
{
	if (nicEditInstance == null)
		nicEditInstance = new nicEditor({fullPanel : true});
	var textArea = document.getElementById(Name);
	if (textArea != null)
	{
		var editor = nicEditInstance.instanceById(Name);
		if (editor == null)
		{
			editor = nicEditInstance.panelInstance(Name);
		}
		else
		{
			nicEditInstance.removeInstance(Name);
		}
	}
}

//This is called by DynamicForm
function saveRichTextEditors()
{
	if (nicEditInstance != null)
		for(index=0;index<nicEditInstance.nicInstances.length;index++)
			nicEditInstance.nicInstances[index].saveContent();
}

function formatCurrency(number)
{
	var number = number.toString().replace(/\$|\,/g,'');
	if (isNaN(number))
		number = "0";
	var sign = (number == (number = Math.abs(number)));
	number = Math.floor(number*100+0.50000000001);
	var cents = number % 100;
	number = Math.floor(number/100).toString();
	if (cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((number.length- (1 + i)) / 3); i++)
		number = number.substring(0, number.length-(4*i+3)) + ',' + number.substring(number.length-(4*i+3));
	return (((sign)?'':'-') + '$' + number + '.' + cents);
}

var currentThumbnail = null;
function selectThumbnail(Name, ID, offBorder, onBorder)
{
	if (currentThumbnail != null)
		currentThumbnail.style.border = offBorder;
	currentThumbnail = document.getElementById('thumbnail' + ID);
	if (currentThumbnail != null)
		currentThumbnail.style.border = onBorder;
	var hiddenField = document.getElementById(Name);
	if (hiddenField != null)
		hiddenField.value = ID;
}

//Password stuff

// Clear prompt from password field, if required.  
function clearPasswordPrompt() 
{    
	var password = document.getElementById("password");    
	password.style.display = "inline";    
	password.focus();    
	var passwordPrompt = document.getElementById("passwordPrompt");    
	passwordPrompt.style.display = "none";  
}

// Set the prompt for the password field, if required.  
function setPasswordPrompt() 
{    
	var password = document.getElementById("password");    
	if (password.value == "") 
	{      
		password.style.display = "none";      
		var passwordPrompt = document.getElementById("passwordPrompt");      
		passwordPrompt.style.display = "inline";    
	}  
}

//Collects client-side desktop information and sens it back to the server
function sendClientCapabilities() {
    var url = accountRoot + "?logvisit=1&width=" + window.screen.width;
    url += "&height=" + window.screen.height;
    url += "&pixelDepth=" + window.screen.pixelDepth;
    url += "&colorDepth=" + window.screen.colorDepth;
    url += "&availHeight=" + window.screen.availHeight;
    url += "&availWidth=" + window.screen.availWidth;
    jQuery.post(url);
}

//Is Password Acceptable
function IsPasswordAcceptable(PasswordStrength, Password) {
    var hasLetter = "[A-Za-z]";
    var hasUppercaseLetter = "[A-Z]";
    var hasLowercaseLetter = "[a-z]";
    var hasNumber = "\\d";
    var hasSymbol = "[~!@\#\$%\^&\*\(\)\+`\-=\?\/\.\,<>]";
    
    if (PasswordStrength == "Weak") {
        if (Password.length < 4)
            return "Must be at least 4 characters in length.";
    }
    else if (PasswordStrength == "Moderate") {
        if (Password.length < 6 || Password.search(hasLetter) == -1 || Password.search(hasNumber) == -1)
            return "Must be at least 6 characters in length with at least one letter and one number.";
    }
    else if (PasswordStrength == "Strong") {
        if (Password.length < 8 || Password.search(hasUppercaseLetter) == -1 || Password.search(hasLowercaseLetter) == -1 || Password.search(hasNumber) == -1 || Password.search(hasSymbol) == -1)
            return "Must be at least 8 characters in length with at least one lowercase letter, one uppercase letter, one number and one symbol (~!@#$%^&*+`-=?/.,<>).";
    }

    return "";
}
