/*============================================================================*/
/*       Copyright (c) 2002-2008 Church of Scientology International          */
/*                         All rights reserved.                               */
/*============================================================================*/
function stripSpaces(x) {
   x = x.replace(/^ */, "");
   x = x.replace(/ +$/, "");
   return x;
}

function isEmpty(x) {
   x = stripSpaces (x.value);
   if (x.length > 0) {
      return false;
   }
   else {
     return true;
   }
}

function isValidEmail(s) {
   var myString      = s.value;
   var myLength      = myString.length;
   var myAt          = "@";
   var myAtIndex     = myString.indexOf (myAt);
   var myPeriod      = ".";
   var myPeriodindex = myString.indexOf (myPeriod);

   if ((myAtIndex == -1) || (myAtIndex == 0) || (myAtIndex >= (myLength - 1))) {
      return false;
   }
   if ((myPeriodindex == -1) || (myPeriodindex == 0) || (myPeriodindex == myLength)) {
      return false;
   }
   if (myString.indexOf (myAt, (myAtIndex + 1)) != -1) {
       return false;
   }
   if ((myString.substring ((myAtIndex - 1), myAtIndex)       == myPeriod) ||
       (myString.substring ((myAtIndex + 1), (myAtIndex + 2)) == myPeriod))  {
      return false;
   }
   if (myString.indexOf (myPeriod, (myAtIndex + 2)) == -1){
      return false;
   }
   if (myString.indexOf (" ") != -1) {
      return false;
   }
   return true;                                 
}

function isValidLength (s, length) {
   return (s.value.length == length);
}

function isLengthBetween (s, length1, length2) {
   return ((s.value.length >= length1) && (s.value.length <= length2));
}

function isValidName (s) {
// if (s.value.search (/^[-,' &A-Za-z]+$/) == -1) {
//    return false;
// }
   return true;
}

function isValidAddress (s) {
// if (s.value.search (/^[-\,\/()%#&'".\ A-Za-z0-9]+$/) == -1) {
//    return false;
// }
   return true;
}

function isValidNumeric (s) {
   if (s.value.search (/^[0-9]+$/) == -1) {
      return false;
   }
   return true;
}

function isValidPin (s) {
   if (s.value.search (/^[A-Za-z0-9]+$/) == -1) {
      return false;
   }
   return (isValidLength (s, 8));
}

function isValidUserId (s) {
   return (isLengthBetween (s, 1, 100));
}

function isValidPassword (s) {
   return (isLengthBetween (s, 6, 30));
}

/*=========================================*/
/*   This the function for the dictionary word select   */
/*========================================*/

function getSelected () {
   selected="";
   if (document.selection) {
      selected=document.selection.createRange().text;
   }
   else {
      if (document.getSelection) {
         selected=document.getSelection();
      }
   }
   return selected;
}

function launch_quickLookup (myPopUpUrl) {
   var mySelectedText=getSelected();
   if (mySelectedText) {
      var myValidText=mySelectedText.toString();
      var myLookupText =(myValidText.replace(/^\W+/,'')).replace(/\W+$/,'');
      showDictionary (myPopUpUrl + '?query=' + myLookupText );
   }
}

/*======================================================*/
/*   This the functions for the windows to open - dico and materials   */
/*======================================================*/

function showDictionary (aUrl) {
   window.open (aUrl,'dictionary','directories=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=10,left=0,width=490,height=580').focus();
}

function showSourceMaterial (aUrl) {
   window.open (aUrl + '#marker','sourcematerial','directories=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=10,left=0,width=700,height=580').focus();
}

function showHelp (aUrl) {
   window.open (aUrl,'helppage','directories=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes,top=10,left=0,width=490,height=580').focus();
}


/*======================================================*/
/*   This the functions for email to a friend - dn/contact/article.html      */
/*======================================================*/



var hexChars = '0123456789ABCDEF';

function makeHexCharCode(c) {
        var cn = c.charCodeAt(0);
        var n1 = parseInt(new String(cn/16));
        var n2 = parseInt(new String(cn%16));
        return hexChars.charAt(n1)+hexChars.charAt(n2);
}

var noEncodeChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

function encodeURL(url) {
        var ret = '';
        for (var i = 0; i < url.length; i++) {
                var c = url.charAt(i);
                if (c == ' ') c = '+';
                else if (noEncodeChars.indexOf(c)<0) {
                        c = '%'+makeHexCharCode(c);
                }
                ret += c;
        }
        return ret;
}   

function sendToAFriend(tgt) {

var u = tgt +  "?dnTitle=" + encodeURL(document.title) + "&dnLink=" + encodeURL(new String(document.location));
window.open (u,'email','toolbar=0,location=0,width=444,height=484,left=0,top=0,status=0,scrollbars=0,resizable').focus();

}

/*======================================================*/
/*   This the functions for add to favorite - dn toolkit                             */
/*======================================================*/

function addToFavorites() {
	if (window.external) {
		window.external.AddFavorite(document.location,document.title);
	} else {
		alert('Browser error: Please manually add this page to your favorites');
	}
}



/*======================================================*/
/*   Pop up back to main window from search snipet                            */
/*======================================================*/

function targetopener(mylink, closeme, closeonly)
{
if (! (window.focus && window.opener))return true;
window.opener.focus();
if (! closeonly)window.opener.location.href=mylink.href;
if (closeme)window.close();
return false;
}




/*======================================================*/
/*                   Stock Dreamweaver Functions                                       */
/*======================================================*/

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_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_findObj(n, d) { //v4.0
  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 && document.getElementById) x=document.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];}
}


/*======================================================*/
/*  give a different flash movie for each visit of the dn home page      */
/*======================================================*/

 function rotateFlashMovies() {
         var v_cookieName = "flashVisitedAlready"; 
         var v_loadNumber = 0;  // keeps track of which movie to load, 1,2,3 etc.

         c = getFlashCookie(v_cookieName) ;

         if (c == -1)
           {
             v_loadNumber = 1;
             document.cookie = "flashVisitedAlready=1";

           }
         else if  (c == 1)
           {
            v_loadNumber = 2;
            document.cookie = "flashVisitedAlready=2";
          
           }  
         else if  (c == 2)
           {
            v_loadNumber = 3;
            document.cookie = "flashVisitedAlready=3";

           }
         else if  (c == 3)
           {

            v_loadNumber = 1;
             document.cookie = "flashVisitedAlready=1";
           } 
       }





/*======================================================*/
/*  Utility functions developed for the video support                             */
/*======================================================*/

/* Decodes a url-encoded string */
function urlDecode(v) {
	var vl = v.length;
	var o = '';
	var c = '';
	for (var i = 0; i < vl; i++) {
		c = v.substring(i, i+1);
		if (c == '+') {
			c = ' ';
		} else if (c == '%') {
			c = v.substring(i+1, i+3);
			c = String.fromCharCode(parseInt('0x'+c));
			i += 2;
		}
		o += c;
	}
	return o;
}

/* Pulls a parameter off of the url and returns it decoded */
function getParameter(n) {
	var parms = document.parms;
	if (!parms) {
		parms = new Object();
		var u = new String(document.location);
		var pos = u.indexOf('?');
		if (pos >= 0 && u.length-1 > pos) {
			var uars = u.substring(pos+1, u.length);
			var uar = uars.split('&');
			var parms = new Object();
			for (var i = 0; i < uar.length; i++) {
				var v = uar[i];
				var ps = v.split('=', 2);
				parms[ps[0]] = urlDecode(ps[1]);
			}
		}
		document.parms = parms;
	}
	return parms[n];
}

/* String replace (only replaces first occurrence) */
function stringReplace(haystack, needle, repl) {
	var p;
	var o = haystack;
	if ((p = haystack.indexOf(needle)) >= 0) {
		o = '';
		if (p) {
			o = haystack.substring(0, p);
		}
		o += repl;
		var endp = p + needle.length;
		if (endp < haystack.length) {
			o += haystack.substring(endp, haystack.length);
		}
	}
	return o;
}

/* parses a string that is in the format name=value%sep%name2=value2 and allows you to choose your separators */
function parseNameValueString(origstr, pairsep, eqsep) {
	var strs = origstr.split(pairsep);
	var strsl = strs.length;
	var outobj = new Object();
	for (var i = 0; i < strsl; i++) {
		var pair = strs[i].split(eqsep, 2);
		outobj[pair[0]] = pair[1];
	}
	return outobj;
}



/*======================================================*/
/*  Netscape video plugin detection (IE has to be done with VBS         */
/*======================================================*/

// NS windows media player detection
var fHasWMP = false;
if (navigator.mimeTypes) {
	fHasWMP = navigator.mimeTypes && navigator.mimeTypes["application/x-mplayer2"] &&  navigator.mimeTypes["application/x-mplayer2"].enabledPlugin;
}

var fHasQT = false;
if (navigator.plugins) {
	for (i=0; i < navigator.plugins.length; i++ ) {
		if (navigator.plugins[i].name.indexOf("QuickTime") >= 0) {
			fHasQT = true;
		}
	}
}



function getDomainAndPort() {
	var domain = new String(document.location);
	var pos = domain.indexOf("/", 7);
	domain = domain.substring(0, pos);
	pos = domain.lastIndexOf("/");
	domain = domain.substring(pos+1, domain.length)
	return domain;
}




/*======================================================*/
/*  Core video code that parses the available video types and can      */
/*  output the actual video                                                                      */
/*======================================================*/

/* Video code */
/*
Properties:
video_formats - mov=Quicktime|wmv=Windows Media
video_modes - mov!hi=DSL!320x240|mov!low=Dialup (Modem)!190x150|mov!med=ISDN (or slow DSL)!240x200|wmv!hi=DSL!320x240|wmv!low=Dialup (Modem)!190x150|wmv!med=ISDN (or slow DSL)!240x200
video_name - /pics/cos/dianetics/en_US/success/video/vid01_%MODE%.%TYPE%

Sample:
var videofmts = videoParseStrings(fmts,modes); // Values as above
for (fmtname in videofmts.formats) {
	var fmt = videofmts.formats[fmtname];
	document.write(fmt.description); // Outputs 'Quicktime' - for example
	for (modename in fmt.modes) {
		var mode = fmt.modes[modename];
		document.write(mode.description);	// Outputs "DSL" or "Dialup (Modem)" etc.
		document.write(mode.width);			// Outputs width, e.g., 240
		document.write(mode.height);		// Outputs height, e.g., 190
	}
	alert(o.formats['mov'].modes['low'].description); // alerts 'Dialup (Modem)'
}
*/
function videoParseStrings(fmts,modes) {
	var n,v;
	var retobj = new Object();
	retobj.formats = parseNameValueString(fmts, '|', '=');

	// Load formats into retobj.formats
	for (n in retobj.formats) {
		v = retobj.formats[n];
		retobj.formats[n] = new Object();
		retobj.formats[n].description = v;

	}

	// Cycle through the modes and assign them to the formats
	var modesobj = parseNameValueString(modes, '|', '=');
	for (var n in modesobj) {
		v = modesobj[n];
		var p0 = n.split('!', 2); // for the mode name
		var p1 = v.split('!', 2); // for the description and the dimensions
		var p2 = p1[1].split('x', 2); // split the dimensions apart
		
		// Make the mode object
		var mode = new Object();
		mode.description = p1[0];
		mode.width = p2[0];
		mode.height = p2[1];

		// Asign it to the mode
		if (!retobj.formats[p0[0]].modes) {
			retobj.formats[p0[0]].modes = new Object();
		}
		retobj.formats[p0[0]].modes[p0[1]] = mode;
	}

	// Return our object
	return retobj;
}

function videoMakePath(namepattern, t, m) {
	return stringReplace(stringReplace(namepattern, '%TYPE%', t), '%MODE%', m);
}

/*
Outputs the video code
Sample:
ed.wmv_error_img = '/pics/cos/dianetics/en_US/myvideos/wmv_error_img.jpg';
ed.mov_error_img = '/pics/cos/dianetics/en_US/myvideos/mov_error_img.jpg';
videoOutput('/pics/cos/dianetics/en_US/myvideos/01_%MODE%.%TYPE%', 'wmv', 'hi', ed);
*/
function videoOutput(namepattern, t, m, obj, ed/* exception data */) {

if (!t) {
  for (var t1 in obj.formats) {
    t = t1;
    break;
  }
}

if (!m) {
  for (var m1 in obj.formats[t].modes) {
    m = m1;
    break;
  }
}

	if (t == 'wmv') { // Windows Media format
		var mode = obj.formats[t].modes[m];
		var fname = videoMakePath(namepattern, t, m);
		var dnp = getDomainAndPort();
		if (fname.indexOf(dnp) < 0) {
			fname = 'http://' + dnp + '/' + fname;
		}
		if (fHasWMP) { // flag already set earlier
			// Load up the code to output
			var tgtcode = "<object onerror=\"alert('There was an error initializing the movie');\" id=\"MediaPlayer1\" width=\"" + mode.width + "\" height=\"" + mode.height + "\" classid=\"CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,0,02,902\" standby=\"Loading Microsoftﾃつｮ Windowsﾃつｮ Media Player components...\" type=\"application/x-oleobject\"> \
				<param name=\"Filename\" value=\"" + fname + "\"> \
				<param name=\"AutoStart\" value=\"true\"> \
				<embed type=\"application/x-mplayer2\" pluginspace=\"http://www.microsoft.com/Windows/MediaPlayer/\" src=\"" + fname + "\" width=\"" + mode.width + "\" height=\"" + mode.height + "\" autostart=true></embed>  \
				</object> ";
		
			var w = window;
			// HACK: NS7 + WMP9 (and probably other version combinations) don't work when embedded in the document, so pop up a window as a hack solution
			if (navigator.appName == 'Netscape') {
				w = window.open(new String(document.location), 'nsvideo', 'width=' + new String(parseInt(mode.width)+10) + ',height=' + new String(parseInt(mode.height)+40));
				w.focus();
				w.document.write('<HTML><HEAD><base href="' + new String(document.location) + '"><TITLE>Video</TITLE></HEAD><BODY TOPMARGIN=0 BOTTOMMARGIN=0 LEFTMARGIN=0 RIGHTMARGIN=0 MARGINWIDTH=0 MARGINHEIGHT=0><TABLE CELLPADDING=0 CELLSPACING=0 BORDER="0" WIDTH="100%" HEIGHT="100%"><TR><TD ALIGN=CENTER VALIGN=MIDDLE>'+tgtcode+'</TD></TR></TABLE></BODY></HTML>');
				w.document.close();
				document.write('<table border=0 cellpadding=0 cellspacing=0 width="' + new String(parseInt(mode.width)+10) + '" height="' + new String(parseInt(mode.height)+40) + '" style="border: solid #000000 1px"><tr><td>&nbsp;</td></tr></table>');
			} else {
				// Just write it out to the document if we are not Netscape
				document.write(tgtcode);
			}
			
		} else {
			if (ed && ed.wmv_error_img) {
				document.write('<a href="http://www.microsoft.com/Windows/MediaPlayer/"><img src="'+ed.wmv_error_img+'" border="0"/></a>');
			}
			return false;
		}
	} else if (t == 'mov') { // Quicktime format
		var mode = obj.formats[t].modes[m];
		var fname = videoMakePath(namepattern, t, m);
		if (fHasQT) {
			document.write("<object width=\"" + mode.width + "\" height=\"" + mode.height + "\"> \
				<param name=\"Filename\" value=\"" + fname + "\"> \
				<param name=\"AutoStart\" value=\"true\"> \
				<embed src=\"" + fname + "\" width=\"" + mode.width + "\" height=\"" + mode.height + "\" autostart=true></embed> \
				</object>");
		} else {
			if (ed && ed.mov_error_img) {
				document.write('<a href="http://www.apple.com/quicktime/download/"><img src="'+ed.mov_error_img+'" border="0"/></a>');
			}
			return false;
		}
	} else { // Unknown format
	}
	return true;
}


/*======================================================*/
/*   Popup Windows: Targeting the Opener  for the pop up extcrs      */
/*======================================================*/

function targetopener(mylink, closeme, closeonly)
{
if (! (window.focus && window.opener))return true;
window.opener.focus();
if (! closeonly)window.opener.location.href=mylink.href;
if (closeme)window.close();
return false;
}


