var isSubmitting = false;

//popup windows used by the system
var contactPopupWin;
var actionPopupWin;
var otherPopupWin;
var popups = new Array;

//turn form validation off- other pages might turn it on later
var validate=0;

//capture mouse events
if(document.captureEvents) {document.captureEvents(Event.MOUSEMOVE);}
document.onmousemove="";
curmenu = 0;

////////////////detect browser/////////////////////////////////////////

var ie, ns, ver, br;

if (navigator.appName == "Netscape") {
   br="ns";ns =1;
} else {
   br="ie";ie=1;
}
ver = navigator.appVersion.substring(0,1);


////////////////Generic image swapping functions///////////////////////

document.lastImgs = new Array;

function PreloadImages() { 
  images = new Array;
  for (x=0; x<PreloadImages.arguments.length; x++) {
  	images[x]=new Image;
  	images[x].src=PreloadImages.arguments[x];
  	}
}

function SwapImage () {
  if (document.images) {
   if (document.lastImgs.length) {
      RestoreImage();
   }
   a = SwapImage.arguments;
   inum = 0;
   for (x = 0; x < a.length; x+=2) {
      oldimg = a[x];
      newimg = a[x+1];
      if (document.images[oldimg].src.indexOf(newimg) == -1) {
         document.images[oldimg].oldsrc = document.images[oldimg].src;
         document.images[oldimg].src=newimg;
      }
      
      document.lastImgs[inum] = oldimg;
      inum++;
   
    }
  }
}

function RestoreImage () {
  if (document.images) {
   for (x = 0; x < document.lastImgs.length; x++) {
      img = document.lastImgs[x];
      document.images[img].src=document.images[img].oldsrc;
   }
   document.lastImgs = new Array;
  }
}

/////////////////Toolbar menu functions////////////////////////

var formlayers = 0; //number of hideable form layers on the page
var clipLeft = 0;
var clipRight = 0;
var clipBottom = 0;
var clipTop = 0;
var toolbarxy = new Array;
toolbarxy[1] = new point(27,129);
toolbarxy[2] = new point(119,129);
toolbarxy[3] = new point(211,129);
toolbarxy[4] = new point(295,129);
toolbarxy[5] = new point(411,129);
toolbarxy[6] = new point(0,0);
toolbarxy[7] = new point(0,0);
var curmenu = 0;

function point (x, y) {
   this.x = x;
   this.y = y;
}

//////Get the coords of any layer
function GetBox (elem)
	{
	var result = new Object;
	
	var left	= 0;
	var top		= 0;

	for (var item = elem; item; item = item.offsetParent)
		{
		left += item.offsetLeft;
		top  += item.offsetTop;
		
		if (item.style.borderLeftWidth)
			{
			var bwid = parseInt (item.style.borderLeftWidth);
			if (!isNaN (bwid))
				left += bwid;
			}
		}
	
	result.left		= left;
	result.top		= top;
	result.right	= left + elem.offsetWidth;
	result.bottom	= top  + elem.offsetHeight;

	return result;
	}

//////Return appropriate layer object for broswer, or 0 if layer doesn't exist
function GetDiv (lyr, nostyle, usedoc) {
   if (typeof(usedoc) == "undefined") {
      var doc = eval(document);
   } else {
      var doc = eval(usedoc);
   }

   if (doc.getElementById) {

         if (doc.getElementById(lyr)) {
          lyr = doc.getElementById(lyr);
          if (!nostyle) {
            lyr = lyr.style;
          }
         } else {
          lyr = 0;
         }
      
   } else {
      if (eval("doc.all."+lyr)) {
         if (!nostyle) {
           lyr=eval("doc.all."+lyr+".style");
         } else {
           lyr=eval("doc.all."+lyr);
         }
      }
   }
   return lyr;
}

//////Show or hide a layer
function ShowDiv(lyr,xCoord,yCoord,show) {
   var vis;
   if (show) {
      vis = "visible";
   } else {
      vis = "hidden";
   }
lyr = GetDiv(lyr);
if (lyr) {
lyr.left = xCoord;
lyr.top = yCoord;
lyr.visibility = vis;   
}
}    

//////Show or hide all layers with hideable form elements (so that menus aren't cut off by forms)
function ShowFormLayers (vis) {
  for (x = 1; x<= formlayers; x++) {
    ShowDiv('formlayer'+x,0,0,vis);
  }
}

/*
Show or hide toolbar button- can't use generic SwapImage, because we needed added functionality
to track which menu is active, hide forms, etc; plus we don't want to set the RestoreImg and
LastImg variables.
*/

function SwapToolbarButton (button,visible) {
   //ignore hide requests on the current menu button
   if (button == curmenu) {
      return;
   }
   //show all form elements
   ShowFormLayers(1);
      
   //first clear all the other toolbar buttons
   for (x=1; x<=7; x++) {
      if (document.images['toolbar_button'+x]) {
         document.images['toolbar_button'+x].src="/images/toolbar_buttons/toolbar_"+x+"_off.gif";
      }
   }
   //then turn one on, if requested
   if (visible==1) {
      //turn off the current menu, if any
      ShowToolbarMenu(0);
      curmenu=0;
      document.images['toolbar_button'+button].src="/images/toolbar_buttons/toolbar_"+button+"_on.gif";
   }
}   

//////////Get the clipping coords of a layer

function GetClip (lyr) {
var x, y;
   if (br == "ns") {
      if (ver <= 4) {
         x = document.layers[lyr].clip.width;
         y = document.layers[lyr].clip.height;
      } else {
         x = parseInt(document.getElementById(lyr).offsetWidth);
         y = parseInt(document.getElementById(lyr).offsetHeight);
      }  
   } else {
      x = document.all[lyr].offsetWidth;
      y = document.all[lyr].offsetHeight;
   }
   
   p = new point(x,y);
   return p;
}

//////////Show or hide a toolbar menu

function ShowToolbarMenu(menu) {
//first hide all the menus
   for (x = 1; x <= 7; x++) {
      ShowDiv('toolbar'+x,toolbarxy[x].x,toolbarxy[x].y,0);
   } 
//if menu = 0 or the current menu, we just wanted to hide them all
   if (menu == 0 || menu==curmenu) {
   //stop chasing the mouse
      document.onmousemove="";
   //there is no active menu
      curmenu=0;      
   //show all form elements
      ShowFormLayers(1);
   return;   
   }
   
//otherwise show the one we want
   //hide all form elements
   ShowFormLayers(0);
   placer = GetDiv('t'+menu+'_placer',1);
   b = GetBox(placer);
   lyr = GetDiv('toolbar'+menu);
   p = GetClip('toolbar'+menu);
   clipRight = b.left + p.x + 5;
   clipLeft = b.left;
   if (menu == 7) {
      clipLeft -= 80;
      clipRight-= 67;
      b.left -= 80;
   }
   clipBottom = b.bottom + p.y + 5;  
   ShowDiv('toolbar'+menu,b.left,b.bottom,1);
   curmenu = menu;
   //capture mouse events
   document.onmousemove=CheckBounds;
   

}

//////Check whether or not the mouse is in the current clipping range, which is set by
//////the active menu

function CheckBounds(e) {
var x, y;
   if (br == "ns") {
      x = e.pageX;
		y = e.pageY;
   } else {
   	x = window.event.clientX;
		y = window.event.clientY;

   }
   if (x < clipLeft || x > clipRight || y < clipTop || y > clipBottom) {
      ShowToolbarMenu(0);
      menu = curmenu;
      curmenu = 99;
      SwapToolbarButton (menu,0);
   }
}


/////////////////////Page switching functions////////////////////


///////Grab a new page- use this for pretty much all links on the site
function GetPage (page, querystring, validate, wrapper) {
   var url;
   //wrap page in index.php unless otherwise instructed
   if (wrapper) {
      url = wrapper;
   } else {
      url = "/index.php";
   }
   //add the page we're requesting to the query string;
   url = url + "?page=" + page;
   //add the rest of the query string;
   if (querystring!="") {
      url = url + "&" + querystring;
   }
   
   //default to validated
   valok = 1;
   
   //if we request validation, do it
   if (validate) {
      valok = valFields();
   }
   
   //if we validated ok, get the page
   if (valok) {
      window.location = url;
   }
}

///////Grab a new page from a popup
function GetPageFromPopup (page, querystring, validate, wrapper) {
   var url;
   //wrap page in index.php unless otherwise instructed
   if (wrapper) {
      url = wrapper;
   } else {
      url = "index.php";
   }
   //add the page we're requesting to the query string;
   url = url + "?page=" + page;
   //add the rest of the query string;
   if (querystring!="") {
      url = url + "&" + querystring;
   }
   
   //default to validated
   valok = 1;
   
   //if we request validation, do it
   if (validate) {
      valok = valFields();
   }
   
   //if we validated ok, get the page into the main site and close the popup
   if (valok) {
      top.opener.location = url;
      top.close();
   }
}


/////////////////Open new window////////////////////////
/*function GetPopup(url, height, width, nameW) {
 var newWin;

 if (typeof nameW == 'undefined') {
   nameW = "horchataContact";
 }

 if (width==-1) {width=480;}
 if (height==-1) {height=510;}
 
 if (eval("typeof "+nameW) != "undefined") {
   if (eval (nameW+".closed") == false) {
      eval (nameW+".close()");
   }
 }

 if (parseInt(navigator.appVersion)>=4) {
 // Vars for centering the new window on Version 4 Browsers
 xTop = screen.width/2 - (width/2);
 yTop = screen.height/2 - (height/2);
 eval (nameW+" = window.open(url, nameW, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=' + xTop + ',top=' + yTop + '')");
 } else {
 eval (nameW+" = window.open(url, nameW, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=150,top=200')");
 }
 

}*/

function GetPopup(url, height, width, nameW, doReturn) {
 var newWin;
 
 if (typeof nameW == "undefined") {
   nameW = "horchataContactPopup";
 }

 if (width==-1) {width=500;}
 if (height==-1) {height=510;}
 
 if (parseInt(navigator.appVersion)>=4) {
 // Vars for centering the new window on Version 4 Browsers
 xTop = screen.width/2 - (width/2);
 yTop = screen.height/2 - (height/2);
 newWin = window.open(url, nameW, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=' + xTop + ',top=' + yTop + '');
 } else {
 newWin = window.open(url, nameW, 'height='+height+',width='+width+',scrollbars=1,resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=150,top=200');
 }
 
 //newWin.resizeTo(width,height);
 newWin.moveTo(xTop,yTop);
 newWin.focus();
 
 if (doReturn) {
   return newWin;
 }

}

/////////////////Hook the enter key for a form field////////////////////////
 
/*example:

 <INPUT type='text' onKeyPress="submitenter(this,event,'login()')">
 
*/
 
function submitenter(myfield,e,action)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13 || keycode == 3)
   {
   eval(action);
   return false;
   }
else
   return true;
}

function submitForm() {
   if (valFields() && isSubmitting == false) {
      isSubmitting = true;
      document.frmMain.submit();
   }
}    

/////////////////Validate email address////////////////////////
function valEmail(str, blankOk, complexOk) {

  if (blankOk == "") {
   blankOk = true;
  }
  
  if (complexOk == "") {
   complexOk = false;
  }  
   
  if (str == "" && blankOk == -1) {
   return false;
  } else {
     var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
     var reg2 = /^(\w|\.|-|_|\+)+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; // valid
     var reg3 = /^(\w|\s|\.|-\+)*<((\w|\.|-|_\+)+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))>$/; //valid (John Miles <john@integritive.com>)
     if (complexOk) {
        if (str && !(!reg1.test(str) && (reg2.test(str) || reg3.test(str)))) { // if not blank, and syntax is invalid 
         return false;
        }
     } else {
        if (str && !(!reg1.test(str) && reg2.test(str))) { // if not blank, and syntax is invalid
         return false;
        }
     }
  }
     return true;
}

//////////////Manage context menus//////////////////////

function showContext (e, menu) {
   currentContextMenu = menu;
	xTop = screen.width/2;
 	yTop = screen.height/2;


   if (br == "ns") {
      x = e.pageX;
		y = e.pageY;
   } else {
   	x = window.event.x;
		y = window.event.y;
   }
   
   //alert (y);
   
   lyr = GetDiv(currentContextMenu);
   lyr.left = x-5;
   lyrbox = GetBox(GetDiv(currentContextMenu,1));
   
   if (y <= yTop) {
   	lyr.top = (y - 5);
  	} else {
  		lyr.top = (y - (lyrbox.bottom - lyrbox.top)) + 5;
  	}
  	
   lyr.visibility = "visible";
   //alert (y+" "+lyr.top);
   contextClip = GetBox(GetDiv(currentContextMenu,1));
   
   document.onmousemove = trackContextMenu;
}

function trackContextMenu(e) {
var x, y;
   if (br == "ns") {
      x = e.pageX;
		y = e.pageY;
   } else {
   	x = window.event.clientX;
		y = window.event.clientY;

   }
   if (x < contextClip.left || x > contextClip.right || y < contextClip.top || y > contextClip.bottom) {
      lyr = GetDiv(currentContextMenu);
      lyr.visibility = "hidden";
   }
}

function hideContextMenu() {
   lyr = GetDiv(currentContextMenu);
   lyr.visibility = "hidden";
}

function getBrowserDimensions() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement &&
      ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  var dim = new Array;
  dim[0] = myWidth;
  dim[1] = myHeight;
  return dim;
}

function addField (form, fieldType, fieldName, fieldValue) {
  if (document.getElementById) {
    var input = document.createElement('INPUT');
      if (document.all) { // what follows should work 
                          // with NN6 but doesn't in M14
        input.type = fieldType;
        input.name = fieldName;
        input.value = fieldValue;
      }
      else if (document.getElementById) { // so here is the
                                          // NN6 workaround
        input.setAttribute('type', fieldType);
        input.setAttribute('name', fieldName);
        input.setAttribute('value', fieldValue);
      }
    form.appendChild(input);
  }
}
