// JavaScript Document
function goToURL(url) {location.href = url;}

function replaceURL(url) {location.replace(url);}

function checkAll(formname,thename,thestatus) { //this unchecks/checks boxes, done especially for inputs with a [] for PHP to parse as an array...
		theform = document.getElementById(formname);
		theinputs = theform.getElementsByTagName('input');
		for(i=0; i<theinputs.length; i++) {
			var regex = new RegExp(thename, "i");
			if(regex.test(theinputs[i].getAttribute('name'))) {
				if(thestatus=='on') {
					theinputs[i].checked = true;
				}
				else {
					theinputs[i].checked = false;	
				}
			}
		}
}


function sendMe(theitem) {
	var theURL = $(theitem).options[theitem.selectedIndex].value;
	if(theURL!='') {
		window.location = theURL;
	}
}

function sendMeURL(theitem,thelocation) {
	//alert(theitem.options[theitem.selectedIndex].value);
	newurl = thelocation + (theitem.options[theitem.selectedIndex].value);
	location = newurl;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function clearField(formfield) {
	var args = arguments.length;
	for (var i=0; i<args;i=i+1){
		//alert(arguments[i]);
		var thefield = document.getElementById(arguments[i]);
		$(thefield).value = '';
	}
}


function clearAndDisable(fields) { //clear and disable form fields
	var args = arguments.length;
	for (var i=0; i<args;i=i+1) {
		$(arguments[i]).value = '';
		$(arguments[i]).disabled = true;
	}
}



function clearAndEnable(field) { //enable form fields
	var args = arguments.length;
	for (var i=0; i<args;i=i+1) {
		$(arguments[i]).value = '';
		$(arguments[i]).disabled = false;
	}
}


function clearDropDown(theFields) {
	var args = arguments.length;
	for (var i=0; i<args;i=i+1) {
		var theList = $(arguments[i]);
		theList.options.length = 0;
		theList.options[0] = new Option('= Select =','');	
	}
}

// Removes leading whitespaces
function LTrim( value ) {	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");	
}

// Removes ending whitespaces
function RTrim( value ) {	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

// Removes leading and ending whitespaces
function trim( value ) {	
	return LTrim(RTrim(value));	
}

function isBlank(theField) {
	if(trim($F(theField))=='') {
		return true;		   
	}
	else {
		return false;	
	}
}

function decision(message, url){
  if(confirm(message)) parent.location.href = url;
}



function popupClose(message) { //a javascript function that replicates our PHP function which outputs javascript!
	alert(message);
	window.close();
}


function popupReload(message) { //a javascript function that replicates our PHP function which outputs javascript!
	alert(message);
	opener.location.reload(true);
	window.close();
}


function validate_email(str) { 
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}
	
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}
	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}
	
	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }
	
	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }
	
	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false;
	 }
	
	 return true;				
}


var MonthNameToNumber = new Array();
MonthNameToNumber["Jan"] = "01";
MonthNameToNumber["Feb"] = "02";
MonthNameToNumber["Mar"] = "03";
MonthNameToNumber["Apr"] = "04";
MonthNameToNumber["May"] = "05";
MonthNameToNumber["Jun"] = "06";
MonthNameToNumber["Jul"] = "07";
MonthNameToNumber["Aug"] = "08";
MonthNameToNumber["Sep"] = "09";
MonthNameToNumber["Oct"] = "10";
MonthNameToNumber["Nov"] = "11";
MonthNameToNumber["Dec"] = "12";

var monthNumberToName = new Array();
monthNumberToName[1] = "January";
monthNumberToName[2] = "February";
monthNumberToName[3] = "March";
monthNumberToName[4] = "April";
monthNumberToName[5] = "May";
monthNumberToName[6] = "June";
monthNumberToName[7] = "July";
monthNumberToName[8] = "August";
monthNumberToName[9] = "September";
monthNumberToName[10] = "October";
monthNumberToName[11] = "November";
monthNumberToName[12] = "December";

function getSelectedText(theField) {
	var thetext = trim($(theField).options[$(theField).selectedIndex].text);	
	return thetext;
}
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 ""
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function whiteBack(thefield) {
	$(thefield).style.backgroundColor = '#ffffff';	
}

function yellowBack(thefield) {
	$(thefield).style.backgroundColor = '#f7f5bd';	
}

function changeIt(thefield) {
	$(thefield).addClassName('activeBox');
	$(thefield).removeClassName('textInput');
}
function changeBack(thefield) {
	$(thefield).addClassName('textInput');
	$(thefield).removeClassName('activeBox');
}

function checkLink(thefield) {
	var theLink = $F(thefield);
	if(theLink.indexOf('http://')==-1) {
		alert('Your link should begin with \'http://\' unless you are linking to a page on this site.');	
	}
}


//SOME FORM + XML STUFF - OFTEN USED IN AJAX FUNCTIONS, OR FORM VALIDATING/RESETTING

function XMLtoForm(xmlFile,node,formfield) { //this function looks for a value in the node, and puts it in the form field
	
	xmlDocument = xmlFile;
	
	if((xmlDocument.getElementsByTagName(node).item(0).firstChild)!=null) { //there is data in the XML node
		var thedata = xmlDocument.getElementsByTagName(node).item(0).firstChild.data;
		var thefield = document.getElementById(formfield);		
		//setInputValue(thefield,thedata); // a "validations.js" function
		$(thefield).value = thedata;
	}
	else {//the XML node has no value, so make the form field blank
		document.getElementById(formfield).value = ""; 
	}
	
}

function XMLtoInnerHTML(xmlFile,node,theid) { //this function takes an XML node value and puts it directly into HTML
	xmlDocument = xmlFile;		
	if((xmlDocument.getElementsByTagName(node).item(0).firstChild)!=null) { //there is data in the XML node
		var thedata = xmlDocument.getElementsByTagName(node).item(0).firstChild.data;
		$(theid).innerHTML = thedata;	
	}
}

function getNode(xmlFile,thenode) {
	var thedata = '';
	xmlDocument = xmlFile;
	if((xmlDocument.getElementsByTagName(thenode).item(0).firstChild)!=null) { //there is data in the XML node
		thedata = xmlDocument.getElementsByTagName(thenode).item(0).firstChild.data;
	}
	return thedata;
}


/* admin cloning stuff */

function alterDiv(needle,newnum) { //this function is used in our killMe function: change div names
	if (z[j].id.substring(0, String(needle).length)==needle) {
			z[j].id=needle+(newnum);
			z[j].name=needle+(newnum);
	}	
}

function nodeMaker(nodeName,newNum) { //changing the name of a node
	var theItem = $(nodeName);
	//alert(theItem);
	theItem.id = nodeName + newNum;
	theItem.name = nodeName + newNum;	
}

function nodeReset(nodeName,theName) { //change the orignal 'to clone' nodes back to their orig names
	nodeName.id = theName;
	nodeName.name = theName;
}


function addPhoto() {// ** cloning/adding an item for upload! ** 

	var nodeToClone = 'vUploadImage';
	
	var totalCount = $F('vUploadCount');

	totalCount = totalCount * 1; //making sure our variable is numeric
	var newCount = totalCount + 1;
	
	//change the names of all our form fields (really just one)
	var fileName = $('vFileName');
	
	nodeMaker('vFileName',newCount);

	var tagRay = $('contentForm').getElementsByTagName('span');
	for(var x=0;x<tagRay.length;x++) {
		if(tagRay[x].id=='innerUpload') { //not sure why IE7 is requiring this, but $('innerUpload') or even getElementById('innerUpload') chokes...
			var innerUpload = tagRay[x];
		}
	}

	nodeMaker('innerUpload',newCount);
	
	caption = $('vCaption');
	nodeMaker('vCaption',newCount);	

	//***** now, lets actually clone the node ******
	var newDiv = $(nodeToClone).cloneNode(true);
	newDiv.id = nodeToClone + newCount;
	newDiv.style.display = 'none';
	
	//reset all the original form names/ids so we can clone the div cleanly next time
	nodeReset(fileName,'vFileName');
	nodeReset(innerUpload,'innerUpload');
	nodeReset(caption,'vCaption');
	
	//finally, show the new div
	var insertHere = $('vInsertMarker');
	insertHere.parentNode.insertBefore(newDiv,insertHere);	

	//finish up - new count in textbox, display div
	$('vUploadCount').value =  newCount;
	Element.show(newDiv);
	
}



function addLink() {// ** cloning/adding a link! ** 

	var nodeToClone = 'vLink';
	
	var totalCount = $F('vLinkCount');

	totalCount = totalCount * 1; //making sure our variable is numeric
	var newCount = totalCount + 1;
	
	//change the names of all our form fields
	var linkText = $('vLinkText');	
	nodeMaker('vLinkText',newCount);
	
	linkLocation = $('vLinkLocation');
	nodeMaker('vLinkLocation',newCount);

	//***** now, lets actually clone the node ******
	var newDiv = $(nodeToClone).cloneNode(true);
	newDiv.id = nodeToClone + newCount;
	newDiv.style.display = 'none';
	
	//reset all the original form names/ids so we can clone the div cleanly next time
	nodeReset(linkText,'vLinkText');
	nodeReset(linkLocation,'vLinkLocation');
	
	//finally, show the new div
	var insertHere = $('vInsertLink');
	insertHere.parentNode.insertBefore(newDiv,insertHere);	

	//finish up - new count in textbox, display div
	$('vLinkCount').value =  newCount;
	Element.show(newDiv);
	
}

function addMP3() {// ** cloning/adding an mp3 upload! ** 

	var nodeToClone = 'vMP3';
	
	var totalCount = $F('vMP3Count');

	totalCount = totalCount * 1; //making sure our variable is numeric
	var newCount = totalCount + 1;
	
	//change the names of all our form fields
	var mp3File = $('vMP3File');	
	nodeMaker('vMP3File',newCount);


	//***** now, lets actually clone the node ******
	var newDiv = $(nodeToClone).cloneNode(true);
	newDiv.id = nodeToClone + newCount;
	newDiv.style.display = 'none';
	
	//reset all the original form names/ids so we can clone the div cleanly next time
	nodeReset(mp3File,'vMP3File');
	
	//finally, show the new div
	var insertHere = $('vInsertMP3');
	insertHere.parentNode.insertBefore(newDiv,insertHere);	

	//finish up - new count in textbox, display div
	$('vMP3Count').value =  newCount;
	Element.show(newDiv);
	
}


function newsletterHighlight(theState,theDiv) {
	if(theState=="on") {
		$(theDiv).style.backgroundImage = 'url(images/subscribe-on.gif)';
		return;
	}
	$(theDiv).style.backgroundImage = 'url(images/subscribe.gif)';
}


function fileCheck(theFileType,theField) {
	var theFile = $F(theField);
	if(trim(theFile)!='') {
		theSplits = theFile.split('.');
		theCount = theSplits.length;
		theExtension = theSplits[theCount-1]; //only grabbing the last .
		if(theExtension!=theFileType) {
			alert('You can only upload '+theFileType+' files in this box.');
			theField.value = '';
		}
	}
}

function formCheck(theFormType) {

	
	var errorcount = 0;
	var errormsg = '';
	
	if(theFormType=="news") { // *********   the news form    ***********************************
		if(isBlank('vHeadline')) {
			/* errorcount++;
			errormsg = errormsg + 'The news headline cannot be blank.\r\n';
			*/
		}
		if(isBlank('vStory')) {
			errorcount++;
			errormsg = errormsg + 'Please enter contents for the main body.\r\n';
		}
	}

	if(theFormType=="tours") { // *********   the tour form    ***********************************
		if(isBlank('vTourName')) {
			errorcount++;
			errormsg = errormsg + 'The tour name cannot be blank.\r\n';
		}
	}

	if(theFormType=="tours") { // *********   the concert form    ***********************************
		if(isBlank('vCity')) {
			errorcount++;
			errormsg = errormsg + 'The city cannot be blank.\r\n';
		}
		if(isBlank('vProvince')) {
			errorcount++;
			errormsg = errormsg + 'The province cannot be blank.\r\n';
		}
		if(isBlank('vFacility')) {
			errorcount++;
			errormsg = errormsg + 'The facility cannot be blank.\r\n';
		}
	}
	
	if(theFormType=="specialFeatures") { // *********   the features form    ***********************************

		if(isBlank('vFeatureTitle')) {
			errorcount++;
			errormsg = errormsg + 'The title cannot be blank.\r\n';
		}
		if(isBlank('vBlurb')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a preview.\r\n';
		}
	}
	
	if(theFormType=="stories") { // *********   the story exchange form    ***********************************

		if(isBlank('vStoryTitle')) {
			errorcount++;
			errormsg = errormsg + 'The title cannot be blank.\r\n';
		}
		if(isBlank('vStory')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a story!\r\n';
		}
		if(isBlank('vAuthor')) {
			errorcount++;
			errormsg = errormsg + 'You must enter the story author!\r\n';
		}
	}	
	
	if(theFormType=="contact") { // *********   the contact form    ***********************************

		if(isBlank('vEmail')) {
			errorcount++;
			errormsg = errormsg + 'You must provide an email address.\r\n';
		}
	}
	
	if(theFormType=="store") { // *********   the store form    ***********************************

		if(isBlank('vPrice')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a price for the product.\r\n';
		}
		if(isBlank('vProductName')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a name for the product.\r\n';
		}
}

	if(theFormType=="newsletter") { // *********   the newsletter form    ***********************************

		if(validate_email($F('vMessageFromEmail'))===false) {
			errorcount++;
			errormsg = errormsg + 'You must provide a valid email address for the author.\r\n';
		}
		if(isBlank('vMessageSubject')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a subject for the newsletter/email.\r\n';
		}
		if(isBlank('vMessageText')) {
			errorcount++;
			errormsg = errormsg + 'You must provide a message!\r\n';
		}
	}
	
	if(theFormType=="photoUpload") {
		if($F('vGalleryID')=='') {
			errorcount++;
			errormsg = errormsg + 'Please select a gallery to upload these photos to.\r\n';
		}
	}


	if(errorcount!=0) {
		alert(errormsg);
		return false;
	}
	else {
		$('vSubmitButton').value = "Please Wait";
		$('vSubmitButton').disabled = true;
		return true;	
	}
}

function checkSignup() {
	var errorcount = 0;
	var errormsg = '';
	
	if(isBlank('vEmail')) {
		errorcount++;
		errormsg = errormsg + 'You must provide an email address.\r\n';
	}
	
	if(validate_email($F('vEmail'))===false) {
		errorcount++;
		errormsg = errormsg + 'You must provide a valid email address.\r\n';
	}	
	
	if(trim($F('AnimCaptcha'))=='') {
		errorcount++;
		errormsg = errormsg + 'You must answer the anti-spam question.\r\n';
	}
	
	if(errorcount!=0) {
		alert(errormsg);
		return false;
	}
	else {
		$('vSubmitButton').value = "Please Wait";
		$('vSubmitButton').disabled = true;
		return true;	
	}
	
}

function checkLastDance() {
	var errorcount = 0;
	var errormsg = '';
	
	if(validate_email($F('vEmail'))===false) {
		errorcount++;
		errormsg = errormsg + 'You must provide a valid email address.\r\n';
	}	
	
	if(isBlank('vLastDanceComments')) {
		errorcount++;
		errormsg = errormsg + 'You must provide a last dance request.\r\n';
	}	
	
	if(trim($F('AnimCaptcha'))=='') {
		errorcount++;
		errormsg = errormsg + 'You must answer the anti-spam question.\r\n';
	}
	
	if(errorcount!=0) {
		alert(errormsg);
		return false;
	}
	else {
		$('vSubmitButton').value = "Please Wait";
		$('vSubmitButton').disabled = true;
		return true;	
	}
}

function checkContact() {
	var errorcount = 0;
	var errormsg = '';
	
	if(validate_email($F('vEmail'))===false) {
		errorcount++;
		errormsg = errormsg + 'You must provide a valid email address.\r\n';
	}	
	
	if(isBlank('vMessage')) {
		errorcount++;
		errormsg = errormsg + 'You must provide a message.\r\n';
	}	
	
	if(trim($F('AnimCaptcha'))=='') {
		errorcount++;
		errormsg = errormsg + 'You must answer the anti-spam question.\r\n';
	}
	
	if(errorcount!=0) {
		alert(errormsg);
		return false;
	}
	else {
		$('vSubmitButton').value = "Please Wait";
		$('vSubmitButton').disabled = true;
		return true;	
	}
}