var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
var isNN = (navigator.appName.indexOf("Netscape")!=-1) ? true : false;
var requiredMinorVersion = 0;
var requiredRevision = 0;
var bagStatus = 0;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
			//alert("flashVer="+flashVer);
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function showFlash(whatMovie,paramString,movieName,W,H,BG,Win,Alignment,whatScale,whatVersion,alternateContent,whatAccess)
{
	var requiredMajorVersion = whatVersion;
	if(whatScale == null || whatScale == '')
	{
		whatScale = 'showAll';
	}
	if(whatAccess == null || whatAccess == '')
	{
		whatAccess = 'sameDomain';
	}
	var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
	if(hasRightVersion)
	{  // if we've detected an acceptable version
    var oeTags = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
    + ' width="'+W+'" height="'+H+'" id="'+movieName+'"'
    + ' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'
    + '<param name="movie" value="'+whatMovie+paramString+'" />'
    + '<param name="menu" value="false" />'
    + '<param name="quality" value="high" />'
    + '<param name="wmode" value="'+Win+'" />'
    + '<param name="bgcolor" value="#'+BG+'" />'
    + '<param name="scale" value="'+whatScale+'" />'
    + '<embed src="'+whatMovie+paramString+'" menu="false" quality="high"'
    + ' wmode="'+Win+'" bgcolor="#'+BG+'"'
    + ' scale="'+whatScale+'"'
    + ' width="'+W+'" height="'+H+'" name="'+movieName+'" align="'+Alignment+'"'
    + ' play="true"'
    + ' loop="false"'
    + ' quality="high"'
    + ' allowScriptAccess="'+whatAccess+'"'
    + ' swliveconnect="true"'
    + ' type="application/x-shockwave-flash"'
    + ' pluginspage="https://www.macromedia.com/go/getflashplayer">'
    + '<\/embed>'
    + '<\/object>';
    document.write(oeTags);   // embed the flash movie
  } 
	else 
	{
		document.write(alternateContent);
  }
}


function checkField(whatValue,whatField)
{
	var whatFieldValue = whatField.value;
	if(whatFieldValue == whatValue)
	{
		whatField.value = '';
	}
}

function checkState(whatState,id)
{
	if( whatState == 'FL')
	{
	  if (document.getElementById)
	  {
	    // browser implements part of W3C DOM HTML
	    // Gecko, Internet Explorer 5+, Opera 5+
	    document.getElementById('FLcounties').style.visibility = 'visible';
	  }
	  else if (document.all)
	  {
	    // Internet Explorer 4 or Opera with IE user agent
	    document.all[id].style.visibility = 'visible';
	  }
	  else if (document.layers)
	  {
	    // Navigator 4
	    document.layers[id].style.visibility = 'visible';
	  }
	}
}

function getWidth()
{
	var frameWidth = '';
  if (self.innerWidth)
  {
	frameWidth = self.innerWidth;
  }
  else if (document.documentElement && document.documentElement.clientWidth)
  {
	frameWidth = document.documentElement.clientWidth;
  }
  else if (document.body)
  {
	frameWidth = document.body.clientWidth;
  }
  return frameWidth;
}

function getHeight()
{
	var frameHeight = '';
  if (self.innerHeight)
  {
	frameHeight = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
  {
	frameHeight = document.documentElement.clientHeight;
  }
  else if (document.body)
  {
	frameHeight = document.body.clientHeight;
  }
  return frameHeight;
}

function checkSize()
{
	var newH = getHeight();
	var newW = getWidth();
}

function storeSize()
{
	document.cookie = "w=" + getWidth();
	document.cookie = "h=" + getHeight();
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return null
}

function checkMatch(whatMatch,whatField,fieldName)
{
	if(document.dataForm[whatMatch].value != null && whatField.value != null && whatField.value != '')
	{
		var matchValue = document.dataForm[whatMatch].value;
		if(matchValue != '')
		{
			if(matchValue != whatField.value)
			{
				alert('Please be sure that the two '+fieldName+' fields match');
				document.dataForm[whatMatch].focus();
			}
		}
	}
}

function getArgs()
{
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split(',');
	for(var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf('=');
		if(pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args;
}

function freshPane(whatFile,whatTitle,w,h,x,y)
{
  var frontPane = open('','frontPane','toolbar=no,width='+w+',height='+h+',left='+x+',top='+y+',menubar=no,location=no,status=yes,scrollbars=yes,resizable=yes');
  frontPane.focus();
  frontPane.document.write('<html>');
  frontPane.document.write('<head>');
  frontPane.document.write('<title>');
  frontPane.document.write(whatTitle);
  frontPane.document.write('</title>');
  frontPane.document.write('</head>');
  frontPane.document.write('<body bgcolor="#ffffff"><div align="center">');
  frontPane.document.write('<table width="100%" height="100%" cellpadding="0" cellspacing="0" border="0"');
  frontPane.document.write(' style="height:100%;">');
  frontPane.document.write('<tr><td width="100%" height="100%" align="center" valign="middle" style="height:100%;">');
  frontPane.document.write('<img src="http://');
  frontPane.document.write(whatFile);
  frontPane.document.write('" galleryimg="no">');
  frontPane.document.write('</td>');
  frontPane.document.write('</tr>');
  frontPane.document.write('</table>');
  frontPane.document.write('</div></body>');
  frontPane.document.write('</html>');
  frontPane.document.close();
}

function verify(f)
{
  var empty_fields = "";
  var fCount = 0;
  var empty_options = "";
  var oCount = 0;
  var errors = "";
  var eCount = 0;
  var msg = "";

  for(var i = 0; i < f.length; i++)
  {
    var e = f.elements[i];
    if(((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional)
    {
      if (((e.value == null) || (e.value == "") || isblank(e.value)) && !e.conditional)
      {
        empty_fields += "\n" + replace(e.name,"_"," ") + " is required";
        fCount += 1
        continue;
      }
      if(e.conditional)
      {
				var whatCondition = e.condition;
				if(document.dataForm[whatCondition].value != 1 || document.dataForm[whatCondition].value == 'Other')
				{
          if ((e.value == null) || (e.value == "") || isblank(e.value))
          {
            empty_fields += "\n" + replace(e.name,"_"," ") + " is required";
            fCount += 1
				  }
				}
      }
      if(e.money)
      {
				for(zz=0;zz<e.value.length;zz++)
				{
				  var v = parseFloat(e.value.substring(zz));
          if (isNaN(v) && v != '.')
          {	  
            errors += "\n" + replace(e.name,"_"," ") + " must be dollars and cents";
            eCount = eCount + 1;
				    break;
          }
				}
      }
      if(e.numeric)
      {
				for(zz=0;zz<e.value.length;zz++)
				{
				  var v = parseFloat(e.value.substring(zz));
          if (isNaN(v))
          {	  
            errors += "\n" + replace(e.name,"_"," ") + " must be numeric";
            eCount = eCount + 1;
				    break;
          }
				}
      }
      if(e.count != null)
      {
          if (e.value.length < e.count)
          {	  
            errors += "\n" + replace(e.name,"_"," ") + " must be at least " + e.count + " characters in length";
            eCount = eCount + 1;
          }
      }
      if(e.minVal != null)
      {
	  var v = parseFloat(e.value);
          if (isNaN(v) || ((e.minVal != null) && (v < e.minVal)))
          {	  
            errors += "\n" + replace(e.name,"_"," ") + " must be greater than " + e.minVal;
            eCount = eCount + 1;
          }
      }
      if(e.maxVal != null)
      {
	  var v = parseFloat(e.value);
          if (isNaN(v) || ((e.maxVal != null) && ( v > e.maxVal)))
          {	  
            errors += "\n" + replace(e.name,"_"," ") + " must be less than " + e.maxVal;
            eCount = eCount + 1;
          }
      }
      if(e.email)
      {
	if(test(e.value) == false)
	{
	  errors += "\nA valid email address is required"
	  eCount += 1;
	}
      }
    }
    if ((e.options) && !e.optional)
    {
      var which = e.options.selectedIndex
      var choice = e.options[which].value
      if ((choice == null) || (choice == "") && !e.conditional)
      {
        empty_options += "\n" + replace(e.name,"_"," ") + " selection is required";
        oCount = oCount + 1;
        continue;
      }
      if(e.conditional)
      {
				var whatCondition = e.condition;
				if(f[whatCondition].value != 1 || f[whatCondition].value == 'Other')
				{
          if ((choice == null) || (choice == ""))
          {
            empty_fields += "\n" + replace(e.name,"_"," ") + " selection is required";
            fCount += 1
				  }
				}
      }
    }
  }

  if ((!empty_fields) && (!empty_options) && !errors)
  {
    return true;
  }
  else
  {
    msg = "Please be sure to complete all selections or fill in all required fields.\n";
    if (empty_fields)
    {
      fieldsVar = "field"
      if(fCount > 1){fieldsVar += "s"}
      msg += "\n" + fCount + " required " + fieldsVar + " left blank.";
      msg += empty_fields += "\n";
    }
    if (errors)
    {
      fieldsVar = "field"
      if(eCount > 1){fieldsVar += "s"}
      msg += "\n" + eCount + " " + fieldsVar + " with invalid entries.";
      msg += errors += "\n";
    }
    if (empty_options)
    {
      choicesVar = "choice"
      if (oCount > 1)
        {choicesVar += "s"}
      msg += "\n" + oCount + " required " + choicesVar + " not selected.";
      msg += empty_options += "\n";
    }
    alert(msg);
    return false;
  }
}

function isLetter(str)
{
  var fieldErrors = ""
  var rex = /[^a-zA-Z\s]/

  if ((str == "") || (str == null))
  {
  fieldErrors = "You must enter text.\n";
  }

  if(rex.test(str))
  {
  fieldErrors += "Invalid data was entered.";
  }

  if (fieldErrors)
  {
  alert(fieldErrors);
  return false;
  }
  else
  {
  return true;
  }
}

function isAlphaNum(str)
{
  var fieldErrors = ""
  var rex = /[^\w]/

  if ((str == "") || (str == null) || isblank(str))
  {
  fieldErrors = "You must enter something.\n";
  }

  if(rex.test(str))
  {
  fieldErrors += "Check that you have only entered letters and-or numbers.";
  }

  if (fieldErrors)
  {
  alert(fieldErrors);
  return false;
  }
  else
  {
  return true;
  }
}

function isblank(s)
{
  for(var i = 0; i < s.length; i++)
  {
    var c = s.charAt(i);
    if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
  }
  return true;
}

function replace(string,text,by) 
{
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

function test(src) 
{
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
}




function fillShipping(whatCheck)
{
  if(whatCheck.checked)
  { 
    document.dataForm.Billing_Address.value = document.dataForm.Shipping_Address.value;
    document.dataForm.Billing_Address2.value = document.dataForm.Shipping_Address2.value;
    document.dataForm.Billing_City.value = document.dataForm.Shipping_City.value;
    document.dataForm.Billing_State.value = document.dataForm.Shipping_State.value;
    document.dataForm.Billing_ZIP_Code.value = document.dataForm.Shipping_ZIP_Code.value;
    document.dataForm.Billing_Phone_Area_Code.value = document.dataForm.Shipping_Phone_Area_Code.value;
    document.dataForm.Billing_Phone_Prefix.value = document.dataForm.Shipping_Phone_Prefix.value;
    document.dataForm.Billing_Phone_Number.value = document.dataForm.Shipping_Phone_Number.value;
    document.dataForm.Billing_Phone_Extension.value = document.dataForm.Shipping_Phone_Extension.value;
  }
  else
  {
    document.dataForm.Billing_Address.value = '';
    document.dataForm.Billing_Address2.value = '';
    document.dataForm.Billing_City.value = '';
    document.dataForm.Billing_State.value = '';
    document.dataForm.Billing_ZIP_Code.value = '';
    document.dataForm.Billing_Phone_Area_Code.value = '';
    document.dataForm.Billing_Phone_Prefix.value = '';
    document.dataForm.Billing_Phone_Number.value = '';
    document.dataForm.Billing_Phone_Extension.value = '';
  }
}

if(window.attachEvent)
{
  window.attachEvent("onload",setListeners);
}

function setListeners()
{
  inputList = document.getElementsByTagName("input");
  for(i=0;i<inputList.length;i++)
  {
    inputList[i].attachEvent("onpropertychange",restoreStyles);
    inputList[i].style.backgroundColor = "";
  }
  selectList = document.getElementsByTagName("select");
  for(i=0;i<selectList.length;i++)
  {
    selectList[i].attachEvent("onpropertychange",restoreStyles);
    selectList[i].style.backgroundColor = "";
  }
}

function restoreStyles()
{
  if(event.srcElement.style.backgroundColor != "")
  {
    event.srcElement.style.backgroundColor = "";
  }
}

function popupCVN()
{
	var dest = "cvn.html";
        var leftPosition = (screen.availWidth - 400) / 2;
        var topPosition = (screen.availHeight - 440) / 2;
        var attributes = "scrollbars=no,resizable=no,width=400,height=440,left=" + leftPosition;
        attributes += ",screenX=";
        attributes += leftPosition;
        attributes += ",top=";
        attributes += topPosition;
        attributes += ",screenY=";
        attributes += topPosition;
        window.open(dest, "cvn_help_window", attributes);
        return false;
}

function colorSwap(whatColor)
{
	if(document.images)
	{
		if(whatColor != null && whatColor != '')
		{
			whatColor = replace(whatColor,' ','_')
			var whatImage = itemColor[whatColor];
			if(whatImage != null)
			{
				currentImage = whatImage;
				document.images.itemImage.src = '/imagefiles/images/mid/'+whatImage+'.jpg';
			}
		}
	}
}

function imageView(whatImage)
{
	if(document.images)
	{
		if(whatImage != null && whatImage != '')
		{
			currentImage = whatImage;
			document.images.itemImage.src = '/imagefiles/images/mid/'+whatImage+'.jpg';
		}
	}
}
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 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 alternateMenu(site)
{
	var altMenu = '<div id="mainMenu"><div id="menuButtons">';
	altMenu += '<a title="tops" href="'+site+'/shop/goodies.asp?category=tops&page=1" id="topsMenuButton">tops</a>';
	altMenu += '<a title="Bottoms" href="'+site+'/shop/goodies.asp?category=bottoms&page=1" id="bottomsMenuButton">bottoms</a>';
	altMenu += '<a title="Hats" href="'+site+'/shop/goodies.asp?category=hats&page=1" id="hatsMenuButton">hats</a>';
	altMenu += '<a title="Dresses" href="'+site+'/shop/goodies.asp?category=dresses&page=1" id="dressesMenuButton">dresses</a>';
	altMenu += '<a title="Beach Gear" href="'+site+'/shop/goodies.asp?category=beach_gear&page=1" id="beachGearMenuButton">beach gear</a>';
	altMenu += '<a href="'+site+'/shop/goodies.asp?category=decor&page=1" id="decorMenuButton">decor</a>';
	if(bagStatus == 1)
	{
		altMenu += '<a href="'+site+'/shop/bag.asp" id="bagMenuButton">my beach bag</a>';
	}
	altMenu += '</div></div>';
	return altMenu;
}

