/* 

    Copyright Notice ========================================================

    This file contains proprietary information of Alpine Internet Solutions. 
    Copying or reproduction without prior written approval is prohibited. 

    Copyright (c) 2000-2003 =================================================

    Purpose: Javascript support functions

    $Id: functions.js,v 1.1 2001/05/31 22:07:10 bcash Exp $
    $Author: bcash $
    $Revision: 1.1 $
    $Date: 2001/05/31 22:07:10 $

    @format.tab-size 4
    @format.use-tabs true
 
*/


var lastMouseX;
var lastMouseY;
var curPopupWindow = null;
var helpWindow = null;


// js Browser Detection
isMac = (navigator.appVersion.indexOf("Mac")!=-1) ? true : false;
NS4 = (document.layers) ? true : false;
IEmac = ((document.all)&&(isMac)) ? true : false;
IE4plus = (document.all) ? true : false;
IE4 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 4.")!=-1)) ? true : false;
IE5 = ((document.all)&&(navigator.appVersion.indexOf("MSIE 5.")!=-1)) ? true : false;
ver4 = (NS4 || IE4plus) ? true : false;
NS6 = (!document.layers) && (navigator.userAgent.indexOf('Netscape')!=-1)?true:false;


function confirmLink( theLink, promptText ) {

    var is_confirmed;

    is_confirmed = confirm( promptText );

    if ( is_confirmed ) {

     // Remove .docs 
     var mylink = theLink.href;
        link = mylink.replace( //.docs/, '');
        theLink.href = link + "&confirmed=Yes";
    }

    return is_confirmed;
} 

function setLastMousePosition(e) {
	if (navigator.appName.indexOf("Microsoft") != -1) e = window.event;
	lastMouseX = e.screenX;
	lastMouseY = e.screenY;
}

function openClickout(url) {
		// Taken out due to inconsistent escape results between java and javascript
        //window.open('/sales/linkout.jsp?url='+escape(url), "_blank", 'width=640,height=480,dependent=no,resizable=yes,toolbar=yes,status=yes,directories=yes,menubar=yes,scrollbars=1', false);
	window.open(url, "_blank", 'width=640,height=480,dependent=no,resizable=yes,toolbar=yes,status=yes,directories=yes,menubar=yes,scrollbars=1', false);
}

function alpineRedir( formName, aobj, url ) {

	var IdElement = eval( "document." + formName + "['" + aobj + "']" );

	if ( IdElement.type == "select-one" ) {
	
		var itemIndex = IdElement.selectedIndex;
		if ( itemIndex != 0 ) {
		
			var rid = IdElement.options[IdElement.selectedIndex].value;
			
			var pos = url.indexOf('[RID]');
			var nurl = url.substr(0,pos) + rid + url.substring(pos+5);
			 alert( "New URL: " + nurl + "." );
			
			 alert( "Field: " + IdElement.name + " Type: " + IdElement.type + " Index: " + IdElement.selectedIndex + " Value: " +  IdElement.options[IdElement.selectedIndex].value  + "." );
			if ( window.confirm('Any unsaved changes will be lost.  Are you sure?') ) {
			
				if (document.images) {
					top.location.replace(nurl);
				} else {
					top.location.href = nurl;
				}
			} else {
				return;
			}
		} else {
			alert( "Option not selected.  Please select an option from the list." );
			return;
		}
		
	}
	
}

function placeFocus() {
	if (document.forms.length > 0) {
		var field = document.forms[0];
		for (i = 0; i < field.length; i++) {
			if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") ) {
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
}

// || (field.elements[i].type.toString().charAt(0) == "s")

function openPopup(url, name, pWidth, pHeight, features, snapToLastMousePosition) {

   closePopup();
	if (snapToLastMousePosition) {
		if (lastMouseX - pWidth < 0) {
			lastMouseX = pWidth;
		}
		if (lastMouseY + pHeight > screen.height) {
			lastMouseY -= (lastMouseY + pHeight + 50) - screen.height;
		}
                lastMouseX -= pWidth;
                lastMouseY += 10;
		features +=	"screenX=" + lastMouseX + ",left=" + lastMouseX + "screenY=" + lastMouseY + ",top=" + lastMouseY;
	}
	curPopupWindow = window.open(url, name, features, false);

}

var win=null;
function openDialog(page,name,w,h,pos,infocus){
	if(pos=="center"){dleft=(screen.width)?(screen.width-w)/2:100;dtop=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!='center') || pos==null){dleft=0;dtop=20}
	settings="width=" + w + ",height=" + h + ",top=" + dtop + ",left=" + dleft + ",scrollbars=no,location=no,directories=no,status=yes,menubar=no,toolbar=no,resizable=no";
	win=window.open(page,name,settings);
	win.focus();
}


function closePopup() {
	if (curPopupWindow != null) {
	   
		if (!curPopupWindow.closed) {
			curPopupWindow.close();
		}
		curPopupWindow = null;
	}
}

function openLookup(baseURL,modified,searchParam) {
	if (modified == '1') baseURL = baseURL + searchParam;
	openPopup(baseURL, "lookup", 350, 300, "width=350,height=300,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}



function pickCalendar(form,field,year,month,day) {
	eval("document."+form+".form_month_"+field+".options["+month+"].selected=true");
	eval("document."+form+".form_day_"+field+".options["+day+"].selected=true");
	eval("document."+form+".form_year_"+field+".options["+year+"].selected=true");
    closePopup();
	return false;
}

function openCalendar(url) {
	openPopup(url, "Calendar", 200, 125, "width=200,height=125,dependent=yes,resizable=yes,toolbar=no,status=no,directories=no,menubar=no", true);
}

function openComboBox(url) {
	openPopup(replaceChar(url, ' ', '%'), "Select", 220, 270, "width=270,height=200,dependent=yes,resizable=yes,toolbar=no,status=no,directories=no,menubar=no,scrollbars=1", true);
}

function replaceChar(s, oldchar, newchar) {
	var retval = '';
	for (i = 0; i < s.length; i++) {
		if (s.charAt(i) == ' ') {
			retval = retval + '%';
		} else {
			retval = retval + s.charAt(i);
		}
	}	
	return retval;
}

function openHelp(url) {
	url = url.replace("#", "%23");
	var browserName = navigator.appName;
	if (helpWindow != null && browserName != "Netscape") { helpWindow.close(); }
	var w = window.open(url, "Help", "width=500,height=400,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,screenX=" + window.screenX + ",left=" + window.screenX + "screenY=" + window.screenY + ",top=" + window.screenY, true);
    	w.focus();
	helpWindow = w;
}

function doPrint() {
	alert("This dialog will be replaced by a new browser window containing a printable version" +
		  " of the current page. The user can then select print from the browsers file menu to"+
		  " print the page. Alternatively, this could be an automatically generated Acrobat file.");
}

function doExport() {
	alert("This dialog will be replaced by a File-Save As dialog. Clicking on save in this dialog will save the contents of the current page to a file (in .csv format).");
}

function listProperties(obj) {
	var names = "";
	for (var i in obj) names += i + ", ";
	alert(names);
}


function insertTS(field,datetime,alias) {
	field.value = "---------------------------------n"+ alias + " " +datetime + "nnn" + field.value;
}

function setFocus() {
    var sidebarSearch;
	// search for a tabIndexed field to focus on
    for(var firstIndex=1; firstIndex < 5; firstIndex ++ ){
	    var nextIndex = firstIndex;
        for (var frm = 0; frm < document.forms.length; frm++) {
            for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
                var elt = document.forms[frm].elements[fld];
			    if ( elt.tabIndex != nextIndex ) continue;
                if ((elt.type == "text" || elt.type == "textarea" || elt.type == "password")
                   && elt.name != "sbstr" &&  elt.name.indexOf("owner") != 0) {
				    elt.focus();
	                if (elt.type == "text") {
	                    elt.select();
	                }
	                return true;
			    } else {
				    nextIndex++;
				    fld = 0;
			    }
		    }
	    }
    }

	// failed to find a tabIndexed field, try to find the field based on it's natural position.
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            // skip buttons, radio, or check-boxes
            // to skip "select" types, remove from if statement
            if (elt.type == "text" || elt.type == "textarea" || elt.type == "password") {
                if (elt.name == "sbstr" && document.forms[frm].name == "sbsearch") { 
                    sidebarSearch = elt; 
                } else if (elt.name.indexOf("owner") != 0) {
                    elt.focus();
                    // select text in text field or textarea
                    if (elt.type == "text") {
                        elt.select();
                    }
                    return true;
                }
            }
        }
    }

    if (sidebarSearch != null) {
       sidebarSearch.focus();
    }
    return true;
}

function setNamedFocus(element_name) {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == element_name) {
                elt.focus();
                if (elt.type == "text") {
                    elt.select();
                }
                return true;
            }
        }
    }
    return true;
}

// removes the leading and trailing spaces from a string, 
// similar to the java.lang.String.trim() function
// added by lturetsky, taken from http://www.voy.com/1888/58.html
function trim(st) {
	var len = st.length
	var begin = 0, end = len - 1;
	while (st.charAt(begin) == " " && begin < len) {
		begin++;
	}
	while (st.charAt(end) == " " && begin < end) {
		end--;
	}
	return st.substring(begin, end+1);
}


function formatPhone (field) {
	field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

	// is this phone number 'escaped' by a leading plus?
	if (0 < ov.length && '+' != ov.charAt(0)) {	// format it
	    // count number of digits
	    var n = 0;
		if ('1' == ov.charAt(0)) {	// skip it
			ov = ov.substring(1, ov.length);
		}

	    for (i = 0; i < ov.length; i++) {
	        var ch = ov.charAt(i);

	        // build up formatted number
	        if (ch >= '0' && ch <= '9') {
	            if (n == 0) v += "(";
	            else if (n == 3) v += ") ";
	            else if (n == 6) v += "-";
	            v += ch;
	            n++;
	        }
	        // check for extension type section; 
	        // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
	        if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
	            x = i;
	            break;
	        }
	    }
	    // add the extension
	    if (x >= 0) v += " " + ov.substring(x, ov.length);

	    // if we recognize the number, then format it
	    if (n == 10 && v.length <= 40) field.value = v;
	}
    return true;
}

function dc () {
    return window.confirm('Are you sure?');
}

function clearcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = false;
            }
        }
    }
}

function setcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = true;
            }
        }
    }
}

function setUsername(uname, fname, lname, suffix) {
	if (uname.value.length == 0) {
		uname.value = 
					fname.value.substring(0,1).toLowerCase() 
					+ lname.value.toLowerCase()
					+ "@"
					+ suffix.value;
	}
}
function setAlias(alias, fname, lname) {
	if (alias.value.length == 0) {
		alias.value = fname.value.substring(0,1).toLowerCase() +
					  lname.value.substring(0,4).toLowerCase();
	}
}

// POPUP WINDOW NUMBER 1 
function popWin(url) {
  	closePopup();
  	curPopupWindow = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=550,height=300",false);
}
function popWin2(url) {
   win = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=720,height=500",false);
   //self.name = "tutWindow";
}
function adminWin(url) {
   win = window.open(url,"win","toolbar=1,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600",false);
}

// Changed name of window for printWin so that Printable views do not disappear
// Newname is popWin, Oldname(changed) was curPopupWindow
function printWin(url) {
  popWin = window.open(url,"win","dependent=no,toolbar=1,directories=0,location=0,status=1,menubar=1,scrollbars=1,resizable=1,width=705,height=400",false);
  popWin.focus();
}

function moveSelectElement2(sourceSelect, targetSelect, sourceLabel, targetLabel) {
	moveSelectElement3(sourceSelect, targetSelect, sourceLabel, targetLabel, false);
}


function moveSelectElement3(sourceSelect, targetSelect, sourceLabel, targetLabel, keepTarget) {
	if (sourceSelect.selectedIndex > -1) {
		for (i=0; i < sourceSelect.length; ++i) {  
			var selectedOption = sourceSelect.options[i];
			if (selectedOption.selected) {
				if (selectedOption.text != sourceLabel) {
					var newOption = new Option(selectedOption.text, selectedOption.value);
					if (targetSelect.options.length > 0 && targetSelect.options[0].text == targetLabel) {
						targetSelect.options[0] = newOption;
					} else {
						targetSelect.options[targetSelect.options.length] = newOption;
					}
				} else {
					sourceSelect.selectedIndex = -1;
				}
			}
		}
		if(!keepTarget)
		{	removeSelectElement3(sourceSelect, sourceLabel);
		}
	}
}


function removeSelectElement3(sourceSelect, sourceLabel)
{	if (sourceSelect.selectedIndex > -1)
	{	for (i=sourceSelect.length-1; i > -1; i--) 
		{	if (sourceSelect.options[i].selected) sourceSelect.options[i] = null;
		}
		if (sourceSelect.length == 0) 
		{	var placeHolder = new Option(sourceLabel, sourceLabel);
			sourceSelect.options[0] = placeHolder;
		}
	}
}


function moveUp(sourceSelect)
{	var sel_id;
	sel_id = sourceSelect.selectedIndex;
	if (sourceSelect.length > 1 && sel_id > 0) //got to have at least 2 items and not the first one is selected
	{	var prevOption = sourceSelect.options[sel_id-1];
		var newOption = new Option(prevOption.text, prevOption.value);
		var selectedOption = sourceSelect.options[sel_id];
		sourceSelect.options[sel_id-1] = new Option(selectedOption.text, selectedOption.value);
		sourceSelect.options[sel_id] = newOption;
		sourceSelect.focus();
		sourceSelect.selectedIndex = sel_id -1;
	}
}


function moveDown(sourceSelect)
{	var sel_id;
	sel_id = sourceSelect.selectedIndex;
	if (sourceSelect.length > 1 && sel_id < sourceSelect.length -1) //got to have at least 2 items and not the last one is selected
	{	var nextOption = sourceSelect.options[sel_id+1];
		var newOption = new Option(nextOption.text, nextOption.value);
		var selectedOption = sourceSelect.options[sel_id];
		sourceSelect.options[sel_id+1] = new Option(selectedOption.text, selectedOption.value);
		sourceSelect.options[sel_id] = newOption;
		sourceSelect.focus();
		sourceSelect.selectedIndex = sel_id + 1;
	}
}

function saveSelected(fromSelObj, toHidObj, delim, empty_label) {
    var i;
	toHidObj.value = '';
    for (i=0; i<fromSelObj.length; i++) {
        if (i > 0) {
            toHidObj.value += delim;
        }
        if (!(fromSelObj.length == 1 && fromSelObj.options[0].value == empty_label)) {
            toHidObj.value += fromSelObj.options[i].value;
        }
    } 
}

function openwizard(url, name, resizable) {
  var win = window.open('', name, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable='+resizable+',width=675,height=550',false)
  if ((win.document.URL == '') || (win.document.URL == 'about:blank')) win.location = url; 
  win.focus ();
}

function escapeUTF(src) {
	var ret = "";
	for (i = 0; i < src.length; i++) {
		var ch = src.charCodeAt(i);
		if (ch <= 0x7F) {
			ret += escape(src.charAt(i));
		} else if (ch <= 0x07FF) {
			ret += '%' + ((ch >> 6) | 0xC0).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
		} else if (ch >= 0x0800) {
			ret += '%' + ((ch >> 12) | 0xE0).toString(16) +
				   '%' + (((ch >> 6) & 0x3F) | 0x80).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
		}
	}
	return ret;
}

function openRefer(url) {
	window.open(url, 'referv2', 'resizable=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=420,height=500', false); 
}

function printpage() {
window.print();
}

   // Tab panels
   
   var currentPanel;
   
   function showPanel(panelNum) {
      //hide visible panel, show selected panel, 
      //set tab
      if (currentPanel != null) {
         hidePanel();
      }
      document.getElementById 
         ('panel'+panelNum).style.visibility = 'visible';
         currentPanel = panelNum;
         setState(panelNum);
   }
   
   function hidePanel() {
      //hide visible panel, unhilite tab
      document.getElementById
        ('panel'+currentPanel).style.visibility = 
         'hidden';
      document.getElementById
        ('tab'+currentPanel).style.backgroundColor = 
        '#ffffff';
      document.getElementById
        ('tab'+currentPanel).style.color = 'navy';
   }
   
   function setState(tabNum) {
      if (tabNum==currentPanel) {
         document.getElementById 
           ('tab'+tabNum).style.backgroundColor = 
           '#ddddff';
         document.getElementById
           ('tab'+tabNum).style.color = 'red';
      }
      else {
         document.getElementById
           ('tab'+tabNum).style.backgroundColor = 
           '#ffffff';
         document.getElementById
           ('tab'+tabNum).style.color = 'navy';
      }
   }
   
   function hover(tab) {
      tab.style.backgroundColor = 'ddddff';
   }



/*

    $Log: functions.js,v $
    Revision 1.1  2001/05/31 22:07:10  bcash
    Initial Add

    Revision 1.1  2001/05/31 21:50:19  bcash
    Added proper comment

*/
