// sets form action (adjust quan., or remove item(s))
function updateCart(formID,action) {
	// make sure quan has value
	if (document.forms[formID].quan.value == "") {
		document.forms[formID].quan.value = 0;
	}
	// set form action for proc page
	document.forms[formID].action.value = action;
	// submit for processing
	document.forms[formID].submit();
}

// sets form action for customer login request
// 3 action states = new account, login, guest
function custLogin(action) {
	if (action=='login' && (document.custForm.user.value=='' || document.custForm.password.value=='')) {
		alert('Please supply your username and password');
	} else {		
		document.custForm.action.value = action;
		document.custForm.submit();
	}
}

// credit card validation
function validateCCNum(cardType,cardNum){	
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMEX":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTERCARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}	
	return result;
}

// validates email address
function echeck(str) {
	msg = "The email address you have provided is invalid.";
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert(msg)
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert(msg)
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert(msg)
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert(msg)
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert(msg)
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert(msg)
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert(msg)
	    return false
	 }

	return true					
}

// validate customer info submission
function validCustInfo(){
	// first name	
	if (document.custForm.billingFirstName.value=="") {
			document.custForm.billingFirstName.focus();
    		alert('Please provide your first name.');
       		return false; 
	}
	// last name	
	if (document.custForm.billingLastName.value=="") {
		document.custForm.billingLastName.focus();
    		alert('Please provide your last name.');
       	return false; 
	}
	// biling address	
	if (document.custForm.billingAddress1.value=="") {
			document.custForm.billingAddress1.focus();
    		alert('Please provide your street address.');
       		return false; 
	}
	// billing country	
	if (document.custForm.billingCountry.value=="") {
			document.custForm.billingCountry.focus();
    		alert('Please provide your country.');
       		return false; 
	}
	// billing country	
	if (document.custForm.billingCity.value=="") {
			document.custForm.billingCity.focus();
    		alert('Please provide your city.');
       		return false; 
	}
	// billing state	
	//if (document.custForm.billingState.value=="") {
			//document.custForm.billingState.focus();
    		//alert('Please provide your state.');
       		//return false; 
	//}
	// billing zip	
	//if (document.custForm.billingPostalCode.value=="") {
			//document.custForm.billingPostalCode.focus();
    		//alert('Please provide your zip code.');
       		//return false; 
	//}
	// billing phone	
	if (document.custForm.billingPhone.value=="") {
			document.custForm.billingPhone.focus();
    		alert('Please provide your phone number in the event we have questions about your order.');
       		return false; 
	}
	// billing email
	if (document.custForm.billingEmail.value=="") {
			document.custForm.billingEmail.focus();
    		alert('Please provide your email address in the event we have questions about your order.');
       		return false; 
	}
	// validate email specified
	if (echeck(document.custForm.billingEmail.value)==false){
		document.custForm.billingEmail.value=""
		document.custForm.billingEmail.focus()
		return false
	}
	// credit card name
	if (document.custForm.cardName.value==""){ 
			document.custForm.cardName.focus();
    		alert('Please provide a credit card name.');
       		return false; 
	}
	// credit card type
	if (document.custForm.cardType.value==""){ 
			document.custForm.cardType.focus();
    		alert('Please provide a credit card type.');
       		return false; 
	}
	// credit card number
	if (document.custForm.cardNumber.value==""){ 
			document.custForm.cardNumber.focus();
    		alert('Please provide a credit card number.');
       		return false; 
	}
	// credit card number
	if (document.custForm.cardExpDate.value==""){ 
			document.custForm.cardExpDate.focus();
    		alert('Please provide a credit card expiration date.');
       		return false; 
	}	
	
	// credit card security code
	if (document.custForm.cardSecCode.value==""){ 
			document.custForm.cardSecCode.focus();
    		alert('Please provide the 3 or 4 digit security code located your credit card.');
       		return false; 
	}	
	
	// format cc number and date
	tmpNum = document.custForm.cardNumber.value;
	rExp = / /gi;
	ccNum = tmpNum.replace(rExp,'');
	ccType = document.custForm.cardType.value;
		
	// validate cc specified
	if (validateCCNum(ccType,ccNum)==false){
		if (document.custForm.tickCount.value < 3){
			alert('The credit card number you entered is not valid.')
			document.custForm.cardNumber.select();
			document.custForm.tickCount.value = document.custForm.tickCount.value + 1;			
		}else{
			alert('We cannot validate the credit card information you have provided. Please contact the box office at (970) 927-3254.')
		}
		return false
	}
	
	// check for use bill flag against values in ship fields
	if (!document.custForm.contribution_amount){
		if (document.custForm.useBillingAddress.checked == false && document.custForm.shipAddress1.value == "" && document.custForm.shipCity.value == "" && document.custForm.shipCountry.value == "" && document.custForm.shipState.value == "" && document.custForm.shipPostalCode.value == "") {
			document.custForm.useBillingAddress.checked = true;
		}
	}	
		
	return true;
}	

// prints current window
function printThis(){
	window.print();		
}


// view image
function viewImg(imgID,w,h) {
	iWin = window.open('windows/viewImg.cfm?imgID=' + imgID, 'blah', 'resizable,scrollbars,width=' + w + ',height=' + h + ',left=25,top=25');
	iWin.focus();
}

// venue seating
function viewVenue(imgID){
	viewImg(imgID,'512','550');
}

// validate a ticket price was selected for event on event detail page
function validTicket(){		
	if (document.eventDetailForm.quantity.value==""){ 
			document.eventDetailForm.quantity.focus();
    		alert('Please provide the number of tickets you wish to purchase.');
       		return false; 
	}
		
	var radio_group = document.eventDetailForm.price;
	// one radio	
	if (!radio_group.length){
		if (radio_group.checked){
			return true;
		}
	}else{
	// multiple radios
    	for( i=0; i < radio_group.length; i++ ) {
		   	if( radio_group[i].checked) {    
           		return true;
        	}
		}
    }
	alert('Please select a ticket price');
	
	return false;
}

// validate a ticket price was selected for event on event detail page
function validPass(){		
	// credit card number
	if (document.passForm.quantity.value==""){ 
			document.passForm.quantity.focus();
    		alert('Please provide the number of passes you wish to purchase.');
       		return false; 
	}
	return true;
}

// submit form request
function submitForm(f){	
	document.forms[f].submit();
}

// photo tour slide
function chgSlide(direction) {		 
	if (document.images) {
		thisPic = thisPic + direction			
		if (thisPic > imgCt) {
			thisPic = 0
		}
		if (thisPic < 0) {
			thisPic = imgCt
		}
		document.myPicture.src=myPix[thisPic];
		document.myPictureText.src=myPixText[thisPic];								
		
	}
}

function validPassRequest(){
	// validate email specified
	if (echeck(document.Form.billingEmail.value)==false){
		document.Form.billingEmail.value=""
		document.Form.billingEmail.focus()
		return false;
	}
	return true;
}

// validate date fields for date search
function validateDateSearch(){
	// start date
	if (document.eventDateSearch.calStartDate.value==""){ 
			document.eventDateSearch.calStartDate.focus();
    		alert('Please provide a starting date for the date range.');
       		return false; 
	}
	// valid date?
	startValid = valideDate('eventDateSearch','calStartDate');
	if (startValid == false){
		return false;
	}	
	// end date
	if (document.eventDateSearch.calEndDate.value==""){ 
			document.eventDateSearch.calEndDate.focus();
    		alert('Please provide a ending date for the date range.');
       		return false; 
	}	
	// valid date?
	endValid = valideDate('eventDateSearch','calEndDate');	
	if (endValid == false){
		return false;
	}
	
	return true;
}

// date validation

var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

function valideDate(form,field){
	var dt=document[form][field]
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }

// apply promo code to order
function applyPromo(){
	if (document.checkout.code.value != ""){
		window.location='index.cfm?method=c.procPromo&code=' + document.checkout.code.value;
	} else {
		alert('Please supply a promotional code');
		return false;
	}
}

function toggleVis(elem_id, action){	
	clearMenus();
	var elem = document.getElementById(elem_id);	
	if (action == 'on'){
		elem.className = 'show_cat';
	} else {
		elem.className = 'hide';
	}
}

function clearMenus(){	
	var menus = new Array()
	menus[0] = "program";
	menus[1] = "student";	
	
	//menus[0] = "program";
	//menus[1] = "audition";
	//menus[2] = "application";
	//menus[3] = "enrollment";
	//menus[4] = "finaid";
	//menus[5] = "aos";
	//menus[6] = "student";
	
	// loop and shutdown
	for (i=0;i<menus.length;i++){		
		document.getElementById(menus[i]).className = 'hide';
	}
}

function ImgChange(imgNum,imgSrc){		
	document.images[imgNum].src = imgSrc;
}

function mediaLogin() {
	if (document.media.password.value == ""){
		alert('You must supply a password');
		return false;
	}
	return true;
}

function downloadFile(file) {
	fWin = window.open('windows/file.cfm?file='+file, 'file_dl', 'resizable,width=5,height=5,left=25,top=25');
}

function doExpdCustLogin(chkd){
	// selecting the option to look up cust info?
	if (chkd){
		new Effect.BlindDown('login_info');
		// go ahead and make request if we already have login vals
		if (document.custForm.custUser.value!='' && document.custForm.custPassword.value!=''){
			 doCustInfoQry();
		}
	} else {
		new Effect.BlindUp('login_info');
		var f=document.custForm;
		// clear all form vals
		for(var i=0;i < f.elements.length;i++){
			// current field
			var field = f.elements[i];
			// determine field has matching xml node, if so parse node value
			if (field.name != "" && field.name != 'custUser'){
				switch(field.type){
					case "text":
						field.value="";
						break;
					case "hidden":
						field.value="";
						break;
					case "select-one":
						// loop over select for match
						field.options.selectedIndex=0;
						break;
				}
			}
		}
	}
		
}

function doCustInfoQry(){
	// ensure we have login and password
	if (document.custForm.custUser.value!='' && document.custForm.custPassword.value!=''){
	
		// http req. for selected customer's current rate groups
		// from /lib/ajax.js
		var httpObj = createRequestObject();	
		// open connection
		httpObj.open("POST",'https://aspenmusicfestival.com/services/qry_cust_info.cfm',true);	
		// modify headers to accept post variables
		httpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		// set return as xml
		if (httpObj.overrideMimeType) {
			httpObj.overrideMimeType('text/xml');
		}
		// set handler              
		httpObj.onreadystatechange = function() {					
			// check status for response
			if (httpObj.readyState == 4) {					
				if (httpObj.status == 200) {
					// parse xml rates returned (different for each browser)				
					if(window.ActiveXObject){ // If IE Windows
						var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
						xmldoc.loadXML(httpObj.responseText);
					} else {					
						var xmldoc = httpObj.responseXML;
					}
					
					if (xmldoc.getElementsByTagName('status').item(0).firstChild.data == 1){				
						// loop over form fields, parse field name for matching tag returned in xml				
						var f=document.custForm;		
						
						for(var i=0;i < f.elements.length;i++){
							// current field
							var field = f.elements[i];
							if (field.type != "button" && field.type != "submit"){
								// determine field has matching xml node, if so parse node value
								if (xmldoc.getElementsByTagName(field.name).length != 0 && field.name != ""){
									switch(field.type){
										case "text":
											field.value=xmldoc.getElementsByTagName(field.name).item(0).firstChild.data;										
											break;
										case "hidden":
											field.value=xmldoc.getElementsByTagName(field.name).item(0).firstChild.data;
											break;
										case "select-one":
											// loop over select for match
											for (var ii = 0; ii < field.length; ii++){
												if (field.options[ii].value==xmldoc.getElementsByTagName(field.name).item(0).firstChild.data){
													field.options.selectedIndex=ii;
												}
											}
											break;
									}
								}
							}
						}					
					}
					
					// invalid password
					if (xmldoc.getElementsByTagName('status').item(0).firstChild.data == 2){
						alert('Invalid password for the account \'' + document.custForm.custUser.value + '\'. Please try again.');
						document.custForm.custPassword.select();
					}
					
					// invalid password
					if (xmldoc.getElementsByTagName('status').item(0).firstChild.data == 0){
						alert('Invalid account \'' + document.custForm.custUser.value + '\'. Please try again.');
						document.custForm.custUser.value="";
						document.custForm.custPassword.value="";
						document.custForm.custUser.focus();
					}
					
				} else {
					alert('There was a problem parsing your request please contact the webaster.');
				}
			}
		}
		// send form values
		httpObj.send('user=' + document.custForm.custUser.value + '&password=' + document.custForm.custPassword.value);
	} else {
		alert('Please provide your aspenmusicfestival.com username and password.');
	}		
}

function doWhatIsAcct(){
	if (document.getElementById('whatIsAcct').style.display=='none'){
		new Effect.BlindDown('whatIsAcct');
	} else {
		new Effect.BlindUp('whatIsAcct');
	}
}

function doContribWarn(){
	if (!confirm('The system has detected that you have more than one contribution in your shopping cart. \n\n To merge the two contributions, click the OK button. \n\n To view your shopping cart and adjust the contributions within it, click CANCEL.')){
		window.location='index.cfm?method=c.viewCart';
	}
}

// forces submit via enter key on cust login
function submitLoginOnEnter(f,evt) {
    evt = (evt) ? evt : event;
    var target = (evt.target) ? evt.target : evt.srcElement;
    var form = f;
    var charCode = (evt.charCode) ? evt.charCode :
        ((evt.which) ? evt.which : evt.keyCode);
    if (charCode == 13) {
		custLogin('login');
		return false;
    }
    return true;
}
