// JavaScript Document
NS4 = (document.layers) ? true : false;

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, '');
}

var hexChars = '0123456789abcdef';

function stringToUnicode(str) {
   convStr = '';
   for (var x = 0;x<str.length;x++) {
      convStr += charToUni(str.charCodeAt(x));
   }
   return convStr;
}

function getHex(i) {
   return hexChars.charAt(i & 0x0f);
}

function hexval(v) {
   return getHex(v >>> 12) + getHex(v >>> 8) + getHex(v >>> 4) + getHex(v);
}

function charToUni(ch) {
   
//    if (ch == 10 || ch == 13 || ch == 92 || ch == 34) {
//        return String.fromCharCode(ch);
//    }
    switch(ch) {
    case 9:
    	return ' ';    	
    case 10:
    	return '\n';    	
    case 13:
    	return '\r';
    case 8211:
    	return '-';
    case 8220:
    case 8221:
    	return '"';
    	break;
    case 8217:
    	return "'";
    	break;
    case 8226:
    	return '-';
    	break;
    case 8230:
    	return '...';
    	break;
    default:
    	return String.fromCharCode(ch);
    	break;
    	/*
    	   if (ch < 32 || ch > 126) {
    		   //alert('check this one!! ' + ch + ': ' + String.fromCharCode(ch) + '!');
    	       return "\\u" + hexval(ch);
    	   }
    	   else 
    	       return String.fromCharCode(ch);
//    	alert('ch: ' + ch + ': ' + String.fromCharCode(ch));
//    	return String.fromCharCode(ch);
    	*/
    }
    return;
    /*
   if (ch == 10) 
       return "\\n";
   else if (ch == 13) 
       return "\\r";   
   else if (ch == 92) 
       return "\\\\";
   else if (ch == 34) 
       return "\\\"";
       
   else    
   //* /
   if (ch < 32 || ch > 126) 
       return "\\u" + hexval(ch);
   else 
       return String.fromCharCode(ch);
   */
}

function JSRefData(theId,desc,parentId,parentDesc) {
this.theId=theId;
this.desc=desc;
this.parentId = parentId;
this.parentDesc = parentDesc;
this.id = theId;
}

var allRefData = new Array();

/*
var regionArr = new Array();
regionArr[0]=new JSRefData('AMERICAN','American','WHITE','White Wines');
regionArr[1]=new JSRefData('BURGUNDY','Burgundy','WHITE','White Wines');
regionArr[2]=new JSRefData('LOIRE','Loire','WHITE','White Wines');
regionArr[3]=new JSRefData('AMERICAN','American','RED','Red Wines');
regionArr[4]=new JSRefData('AUSTRALIAN','Australian','RED','Red Wines');
regionArr[5]=new JSRefData('BURGUNDY','Burgundy','RED','Red Wines');
regionArr[6]=new JSRefData('RHONE','Rhone','RED','Red Wines');
regionArr[7]=new JSRefData('BORDEAUX','Bordeaux','RED','Red Wines');
regionArr[8]=new JSRefData('ALL','(All)','SPARKLING','Champagne and Sparkling Wines');

allRefData['WINE']=regionArr;
*/
/****************************************************************************************
 * Function     - Function to populate a select with ref data options with a matching parent
 *                Removes all options starting with the indexToRemoveFrom, in case
 *                there's a 'select one' option or something
 * return       - Nothing
 ****************************************************************************************/
function populateFilteredRefData(type,theSelect,parentId,indexToRemoveFrom) {
    var theArray = allRefData[type];
    //alert('parent: ' + parentId);
    //alert('the array ' + theArray.length);
    //    if (parentId==null || parentId=='')
    //    return;
    if (parentId == null)
        parentId = '';
    if (parentId==null || parentId=='')
        return;
    if (theArray == null) {
        return;
    }
    var arrSize = theArray.length;

    theSelect.options.length=indexToRemoveFrom;
    var theIndex = indexToRemoveFrom;
    for (x in theArray) {
        if (theArray[x].parentId == parentId) {
            theSelect.options[theIndex++] = new Option(theArray[x].desc,theArray[x].id);
        }
    }
}

function isValidFileExt(fileName) {
    var validExtStr = 'jpg, jpeg, gif';
    var theIndex = fileName.lastIndexOf('.');
    if (theIndex <= 0 || theIndex == (fileName.length + 1)) {
        return false;
    }
    var fileExt = fileName.substring(theIndex+1);
    var validExtensions = validExtStr.toLowerCase().split(/,[\s]*/);
    var isValid = false;
    for (var x=0;x<validExtensions.length;x++) {
        if (fileExt.toLowerCase() == validExtensions[x]) {
            isValid = true;
        }
    }
    if (!isValid) {
        return false;
    }
    return true;
}

function submitFormOnEnter(event, functionToCall) {
    if (functionToCall == null || typeof(functionToCall) == 'undefined') {
        return;
    }
    var code = 0;
    if (NS4) {
        code = event.which;
    } else {
        code = event.keyCode;
    }
    if (code==13) {
        eval(functionToCall);
    }
}


function useMultipartForm() {
    document.forms[0].encoding='multipart/form-data';
}

// Image swap in menus

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function openPageForLink(actionId,moduleId)
    {
        document.forms[0].ACTION_ID.value=actionId;
        document.forms[0].MODULE_ID.value=moduleId;
        document.forms[0].FROM_TOP_NAV.value="true";
        document.forms[0].target="_self";
        epcSubmitForm('0');
    }
        

/* pop-up window function */

function selectWin(source,h1,w1){
 newWin = window.open(source,'','height=' + h1 + ',width=' + w1 + ',top=10,left=0');
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}



/* print function */

function printWindow() {
bV = parseInt(navigator.appVersion);
if (bV >= 4) window.print();
}



// Date

var aDay        = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var aMonth      = new Array("January","February","March","April","May","June","July","August","September","October","November","December")


function DateFormat(xdate,x) {
  /*
    Date Format function to be used in internally by the Showdate function.
    Returns either: d, dd, ddd, dddd, m, mm, mmm, mmmm, y, yy, yyy, yyyy.
    eg. Sun Sep 28 09:22:08 EDT 2003  returns  28, 28, Sun., Sunday, 9, 09, Sep., September, 03, 03, 03, 2003
    Sun Sep 28 09:22:08 EDT 2003 = 28 28 Sun. Sunday, 9 09 Sep. September, 03 03 03 2003
  */
  x = x.toLowerCase();
  return (((x == "d")  ? xdate.getDate() : ((x == "dd") ? ((xdate.getDate() <= 9) ? "0"+xdate.getDate() : xdate.getDate()) : ((x == "ddd") ? aDay[xdate.getDay()].substring(0,3)+". " : ((x == "dddd") ? aDay[xdate.getDay()]+", " : ((x == "m")  ? xdate.getMonth()+1 : ((x == "mm") ? (((xdate.getMonth()+1) <= 9) ? "0"+(xdate.getMonth()+1) : xdate.getMonth()+1) : ((x == "mmm") ? aMonth[xdate.getMonth()].substring(0,3) : ((x == "mmmm") ? aMonth[xdate.getMonth()] : ((x == "y" || x == "yy" || x == "yyy") ? xdate.getFullYear().toString().substring(2,4) : ((x == "yyyy") ? xdate.getFullYear().toString() : "")))))))))))
}


function Showdate(_date, _var1, _var2, _var3, _var4, _del) {


  var today       = (_date == null) ? new Date() : new Date(_date);
  _del =  ((_del == null) ? " " : _del);
  return ( DateFormat(today, _var1) + DateFormat(today, _var2) + ((_var2 != "")? _del : "") + DateFormat(today, _var3) + ((_var3 != "")? _del : "") + DateFormat(today, _var4))
}

function checkTextInTextareas() {
  for(i=0; i<document.forms[0].elements.length; i++)
  {
    if(document.forms[0].elements[i].type=="textarea")
    {
      document.forms[0].elements[i].value=stringToUnicode(document.forms[0].elements[i].value);
    }
  }
}

function doActionOLD(theAction,doValidation) {
    checkTextInTextareas();
    //  document.forms[0].pageText.value=stringToUnicode(document.forms[0].pageText.value);
    if (doValidation && !Validator.isFormValid()) {
        return;
    }
    if (theAction) {
    	document.forms[0].action=theAction;
    }
    document.forms[0].submit();
}

function doAction(theAction,doValidation,strWindowName) {
	Util.doAction(theAction,doValidation,'frmMain',strWindowName);
	return;
/*	
	$('.frmMain .error').removeClass('error');
	$('.validationError').hide();
    checkTextInTextareas();
    
    if (doValidation && !Validator.isFormValid()) {
    	$('.validationError').html(Validator.errorMessage).show();
        return;
    }
    if (theAction) {
    	document.forms[0].action=theAction;
    }
    if (strWindowName) {
    	document.forms[0].target=strWindowName;
    }
    document.forms[0].submit();
*/    
}

function doActionInParent(theAction,doValidation) {
	doActionInWindow(theAction,doValidation,'MAIN');
//    if (doValidation && !Validator.isFormValid()) {
//        return;
//    }
//    document.forms[0].action=theAction;
//    document.forms[0].target='MAIN';//window.opener;
//    document.forms[0].submit();
    this.close();
}

function showLinkInPopup(theLink, theWidth, theHeight) {
    this.window.name='MAIN';
  if (theWidth == null) theWidth=648;
  if (theHeight == null) theHeight=450;
  var theWin = window.open(theLink,"COS_POPUP",'width='+theWidth+',height='+theHeight+'alwaysRaised=yes,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes');
  theWin.focus();
}

function doActionInPopup(theAction, theWidth, theHeight) {
    this.window.name='MAIN';
  if (theWidth == null) theWidth=648;
  if (theHeight == null) theHeight=450;
  var theWin = window.open("","COS_POPUP",'width='+theWidth+',height='+theHeight+'alwaysRaised=yes,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes');
  document.forms[0].target="COS_POPUP";
  document.forms[0].isPopup.value="true";
  document.forms[0].action=theAction;
  document.forms[0].submit();
  theWin.focus();
  //changeTarget();
  document.forms[0].target="_self";
  document.forms[0].isPopup.value="false";
}

function doActionInBigPopup(theAction) {
  var theWin = window.open("","COS_POPUP",'alwaysRaised=yes,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no');
  document.forms[0].target="COS_POPUP";
  document.forms[0].isPopup.value="true";
  document.forms[0].action=theAction;
  document.forms[0].submit();
  theWin.focus();
  //changeTarget();
  document.forms[0].target="_self";
  document.forms[0].isPopup.value="false";
}

// function to "check" a radio button
function pickRadio(radioName,valueToPick) {
    var radioArray = eval('document.forms[0].'+radioName);
    for (var x=0;x<radioArray.length;x++) {
        if (radioArray[x].value==valueToPick) {
            radioArray[x].checked=true;
            return;
        }
    }
    return;
}

// function to return the value of the checked radio button
function getCheckedRadio(radioName, theForm) {
    if (theForm == null) {
        theForm = eval('document.forms[0]');
    }
    var radioArray = theForm[radioName];
    if (typeof(radioArray.length) == 'undefined') {
      return (radioArray.checked ? radioArray.value : '');
    }
    for (var x=0;x<radioArray.length;x++) {
        if (radioArray[x].checked == true)
        {
            return radioArray[x].value;
        }
    }
    return '';
}

function showSelectedOption(theSelect,valueToSelect) {
    //alert('selecting ' + valueToSelect + ' in ' + theSelect.name);
    var length=theSelect.length;
    for (var i=0;i<length;i++) {
        if (theSelect.options[i].value==valueToSelect) {
            theSelect.selectedIndex = i;//options[i].selected=true;
            return;
        }
    }
}

function selectOption(theSelect,valueToSelect) {
    var length=theSelect.options.length;
    for (var i=0;i<length;i++) {
        if (theSelect.options[i].value==valueToSelect) {
            theSelect.options[i].selected=true;
            return;
        }
    }
}

function showAllSelectedOptions(theSelect,valueToSelectArr)
{
    var length=theSelect.options.length;
    for (var x=0;x<valueToSelectArr.length;x++) {
        for(var i=0;i<length;i++) {
            if(theSelect.options[i].value==valueToSelectArr[x])
            {
                theSelect.options[i].selected=true;
                break;
            }
        }
    }
}

// used to mark all options selected for the add/remove boxes
function selectAllSelected(theSelect) {
    for (var x=0;x<theSelect.options.length;x++) {
        theSelect.options[x].selected=true;
    }
}

function removeOption(theSelect,optionIndex) {
    for (var x=optionIndex; x<(theSelect.options.length-1); x++) {
        theSelect.options[x].text = theSelect.options[x+1].text;
        theSelect.options[x].value = theSelect.options[x+1].value;
    }
    theSelect.options.length = theSelect.options.length-1;
}

function viewMessage(theMessage) {
    var childWin = window.open("","MESSAGE",'alwaysRaised=yes,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width=400,height=300');
    childWin.document.writeln('<link rel="stylesheet" type="text/css" href="/css/style.css"><b>Full Message:</b><br><br>' + theMessage);
}

function Guest() {
}

Guest.prototype.fromForm = function(theForm) {
    this.guestId = theForm.guestId.value;
    this.memberId = theForm.memberId.value;
    this.title = theForm.title.value;
    this.firstName = theForm.firstName.value;
    this.lastName = theForm.lastName.value;
    this.email = theForm.email.value;
    this.isChild = (theForm.child && theForm.child.checked ? 'Y' : 'N');
	if (theForm.ALL_HIDDEN_FIELDS && (theForm.ALL_HIDDEN_FIELDS != null) && ('true' == theForm.ALL_HIDDEN_FIELDS.value)) { 
	    this.isMember = theForm.isMember.value;
	    this.isFallGuest = theForm.isFallGuest.value;
	} else {
	    this.isMember = getCheckedRadio('isMember',theForm) == 'Y';
	    this.isFallGuest = getCheckedRadio('isMember',theForm) == 'FG';
	}
}

Guest.prototype.toValString = function() {
	return this.toString();
    //return this.guestId+' ~ '+this.title+' ~ '+this.firstName+' ~ '+this.lastName+' ~ '+ this.email+' ~ '+this.isMember+' ~ '+this.isFallGuest +' ~ '+this.isChild + ' ~ ' + this.memberId;
}

Guest.prototype.toString = function() {
    return '{guestId:\'' + this.guestId+
    	'\',title:\''+this.title+
    	'\',firstName:\'' + Util.escapeQuote(this.firstName)+
    	'\',lastName:\'' + Util.escapeQuote(this.lastName)+
    	'\',email:\''+ Util.escapeQuote(this.email)+
    	'\',isMember:\''+this.isMember+
    	'\',isFallGuest:\''+this.isFallGuest+
    	'\',chargeAccount:\''+this.chargeAccount+
    	'\',isChild:\''+this.isChild+
    	'\',memberId:\''+this.memberId+'\'}';
}

Guest.prototype.toTextString = function() {
//alert('toTextString');
    return (this.title == '' ? '' : this.title+' ')+this.firstName+' '+this.lastName+(this.isMember=='Y' ? ' - Member' : (this.isFallGuest ? ' - Spring Visitor ' : ' - Non-member') + (this.isChild == 'Y' ? ' (child)' : ''))+(this.chargeAccount=='Y' ? ', Account Charged' : '');
}

/**
* expects a string[] of the values (the old way)
*/
Guest.prototype.setValues = function(theVal) {
return this.initValues(theVal);
/*
  var vals = theVal.split(' ~ ');
  if (vals.length < 8) {
      //alert('wrong number of vals: ' + vals.length + ': ' + theVal);
  }
  this.guestId=vals[0];
  this.title=vals[1];
  this.firstName=vals[2];
  this.lastName=vals[3];
  this.email=vals[4];
  this.isMember=vals[5];
  this.isFallGuest=vals[6];
  this.isChild=vals[7];
  if (vals.length >= 9) {
      this.memberId=vals[8];
  } else {
      this.memberId = 0;
  }
  
  */
}

/**
* expects values in a "map"/object form
*/
Guest.prototype.initValues = function(valMap) {
//alert('initValues, options: ' + valMap);
eval('var options = ' + valMap);
//alert('options: ' + options);
  this.guestId=(options.guestId ? options.guestId : 0);
  this.title=options.title;
  this.firstName=options.firstName;
  this.lastName=options.lastName;
  this.email=options.email;
  this.isMember=options.isMember;
  //alert(options.isFallGuest + '?? ' + (options.isFallGuest ? 'Y' : 'N'));
  if (options.isFallGuest) {
  	this.isFallGuest=options.isFallGuest;
  }
  this.chargeAccount=options.chargeAccount;
  this.isChild=options.isChild;
  if (options.memberId) {
      this.memberId=options.memberId;
  } else {
      this.memberId = 0;
  }
  //alert('final: ' + this.toValString());
}

function showLoginBox() {
    this.window.name='MAIN';
  var theWidth=450;
  var theHeight=350;
  var theWin = window.open("","COS_POPUP",'alwaysRaised=yes,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+theWidth+',height='+theHeight+',screenX=350,screenY=100');
  document.forms[0].target="COS_POPUP";
  document.forms[0].isPopup.value="true";
  document.forms[0].action='/general/login'
;
  document.forms[0].submit();
  theWin.focus();
  //changeTarget();
  document.forms[0].target="_self";
  document.forms[0].isPopup.value="false";
}


function focusFirstElement() {
  try {
    var fElem=null;
    if (!document.forms[0]) {
        return;
    }
    var elems = document.forms[0].elements;
    for (var x=0; x<elems.length;x++) {
        if (elems[x].type != 'hidden') {
            fElem = elems[x];
            break;
        }
    }
    //alert('focusing:' + fElem.name);
    if (fElem != null) {
        fElem.focus();
    }
  } catch (e) {
  }
}

//*****************************************************************************
//****************** AUTOCOMPLETE *********************************************
//*****************************************************************************

// callback when someone selects a name from the autocomplete
var Autocomplete = new Object();
Autocomplete.selectMemberName = function(event, data, formatted) {
		var hidden = $('#hdnMemberId'); 
		hidden.val(data[1]);
}


//-->

