/* Show / Hide popover */
function togglePop(pop) {
	new Effect.toggle($(pop),'appear');
}

/* Activate page */
function activePage(page) {
	if ($(page)) {
		$(page).addClassName('active')
	}
}

/* Active Question - FAQ page */
var activeQuestion;
function activateQuestion(thisQuestion) {
	if(activeQuestion) activeQuestion.className = '';
	thisQuestion.className = 'active';
	activeQuestion = thisQuestion;
}

/* Displays Calendar */
function displayCal() {
	new Effect.SlideDown('calendarDropdown');
	$('displayCalButton').replace('<img src="http://www.blueman.com/img/button_minus.gif" id="hideCalButton" alt="Hide" class="addbtn hand" onclick="hideCal()" />');
}

function hideCal() {
	new Effect.SlideUp('calendarDropdown');
	$('hideCalButton').replace('<img src="http://www.blueman.com/img/button_plus.gif" id="displayCalButton" alt="Add" class="addbtn hand" onclick="displayCal()" />');
}

/* Simple Popup Trigger(er) */
function popup(target,width,height) {
	window.open(target,'popup','status=0, resizable=1, scrollbars=1, width='+width+', height='+height);
}

/* Linking for Sliders */
function goToPage(url) {
	window.location.href = url;
}

/* Displays Schedule Email Box Prompt */
function toggleEmail() {
	// check to see if the other element is visible first, if so, hide it
	if(document.getElementById('schedulePhone').style.display != 'none') {
	  new Effect.toggle($('schedulePhone'),'appear');
	}
	new Effect.toggle($('scheduleEmailDiv'),'appear');
}

/* Displays Schedule Phone Box Prompt */
function togglePhone() {
	// check to see if the other element is visible first, if so, hide it
	if(document.getElementById('scheduleEmailDiv').style.display != 'none') {
	  new Effect.toggle($('scheduleEmailDiv'),'appear');
	}
	new Effect.toggle($('schedulePhone'),'appear');
}

function revertChanges(id) {
	switch(id) {
	    case 'scheduleEmailDiv':
		  $(id).innerHTML = emailScheduleHTML;
		  break;
		case 'schedulePhone':
		  $(id).innerHTML = phoneScheduleHTML;
		  break;
	}
}

function groupSalesContactSwap(curstage, nextstage) {
  var cs = document.getElementById(curstage);
  var ns = document.getElementById(nextstage);
  
  new Effect.toggle(cs, "appear");
  if(nextstage == 'contactContent') {
	document.groupSalesContact.ContactName.value = '';
	document.groupSalesContact.ContactEmail.value = '';
	document.groupSalesContact.ContactSubject.value = '';
	document.groupSalesContact.ContactMessage.value = '';
	document.groupSalesContact.ContactMessage.innerHTML = '';
  }
  setTimeout('new Effect.toggle($("' + nextstage + '"), "appear")', 1000);
}


// 22-jan-08, mway:
// Set box html to reset after timeout because clicking 'email' or 'phone' again after form was submitted caused the box to be visible indefinitely
// Changed onsuccess condition to use match() vs string equivalence because cake adds the file's parse time at the end of the file
function emailSchedule(cityURL) {
  if(checkdata('ScheduleEmail') == false) {
	return false;
  } else {
	var url = '/tickets/'+cityURL+'/emailSchedule';
	new Ajax.Request(url, {
	  method: 'post',
	  parameters: Form.serialize('emailForm'),
	  onSuccess: function(response) {
	    if(response.responseText.match('success')) {
		  $('scheduleEmailDiv').innerHTML = '<h2>A copy of the schedule has been sent to your email.</h2>';
		  setTimeout('toggleEmail()',3000);
		  setTimeout('revertChanges("scheduleEmail")', 4000);
		}
	  },
	  onFailure: function(response) {
        $('scheduleEmail').innerHTML = '<h2>There was an error - please try again.</h2>';
		setTimeout('toggleEmail()', 3000);
		setTimeout('revertChanges("scheduleEmail)', 4000);
	  }			
	});
  }
}


function phoneSchedule(cityID) {
  if(checkdata('SchedulePhone') == false) {
	return false;
  } else {
	var url = '/tickets/'+cityID+'/phoneSchedule';
	new Ajax.Request(url, {
	  method: 'post',
	  parameters: Form.serialize('phoneForm'),
	  onSuccess: function(response) {
		if(response.responseText.match('success')) {
		  $('schedulePhone').innerHTML = '<h2>A copy of the schedule has been sent to your phone.</h2>';
		  setTimeout('togglePhone()',3000);
		  setTimeout('revertChanges("schedulePhone")', 4000);
		}
	  },
	  onFailure: function(response) {
        $('scheduleEmail').innerHTML = '<h2>There was an error - please try again.</h2>';
		setTimeout('togglePhone()', 3000);
		setTimeout('revertChanges("schedulePhone)', 4000);
	  }			
	});	
  }
}


function postContactForm(cityURL) {
  if(checkContactForm() != true) {
	return false;
  } else {
	var url = '/tickets/' + cityURL + '/groupSalesContact/processContact';
	new Ajax.Request(url, {
	  method: 'post',
	  parameters: Form.serialize('groupSalesContact'),
	  onLoading: function(foo) {
		groupSalesContactSwap('contactContent', 'contactLoading');
	  },
	  onSuccess: function(response) {
	    if(response.responseText.match(/^success/)) {
		  document.getElementById('contactNotice').innerHTML = '<div align="center">' +
		    'Your inquiry has been submitted!<br />' +
		    'You will receive a response in a timely fashion.<br />' +
			'Thank you for your interest.' +
			'</div>';
			setTimeout('groupSalesContactSwap("contactLoading", "contactNotice")', 1900);
			setTimeout('groupSalesContactSwap("contactNotice", "contactContent")', 8000);
		} else {
		  document.getElementById('contactNotice').innerHTML = '<div align="center">' +
		    'It seems like there was a problem.<br />' +
		    'Please submit your inquiry again.<br />' +
			'We apologize for the inconvenience.' +
			'</div>';
			setTimeout('groupSalesContactSwap("contactLoading", "contactNotice")', 1900);
			setTimeout('groupSalesContactSwap("contactNotice", "contactContent")', 5000);
		}
		
	  },
	  onFailure: function(response) {
	    if(!response.responseText.match('success')) {
		  document.getElementById('contactNotice').innerHTML = 'Failed.<br />' +
		    'Cry about it.';
		  setTimeout('groupSalesContactSwap("contactLoading", "contactNotice")', 1900);
		}
	  }			
	});
  }
}


/********************************************************************
 * Validate Email
 *******************************************************************/
function echeck(str) {  
  // Use regex for validation. -mway 22-jan-08
  /* Rules:
  - must start with a letter, then can have any combination of a-z 0-9 . - afterward
  - may use subdomains, sub-sub domains, ...
  - domain extension must be 2-4 letters long.
  - must contain @ sign
  - may not include characters not in the following list: a-z 0-9 . _ - @
  - may use IP in place of domain - format is username@[0.0.0.0]
  */
  		
  var ex = /^([a-z]+[\w-]*\.?)+@([\w-]+\.)+[a-z]{2,4}$/i;
  var eipx = /^([a-z]+[\w-]*\.?)+@\[(\d{1,3}\.){3}\d{1,3}\]/;
  var invalid = /[^\w-.@\[\]]/i;
  if(str && (str.match(ex) || str.match(eipx)) && !str.match(invalid)) {
    return true;
  } else {
    return false;
  }		
}


/********************************************************************
 * Validate Phone Number
 *******************************************************************/
function pcheck(str) {  
  /* Rules:
  - US numbers only, other formats may be added
  */
  
  str = str.replace(/[^\d]/g, '');  
  var ex = /^\d{10}$/;
  if(str && str.match(ex)) {
    return true;
  } else {
    return false;
  }		
}


/********************************************************************
 * Validate Extraneous Fields, eg. /tickets/[city]/groupSalesContact
 *******************************************************************/
function fcheck(id) {  
  var e = document.getElementById(id);
  if(e.id.match(/^Contact/)) { var name = e.id.replace(/^Contact/, ''); }
  if(id == 'ContactEmail') {
    ex = /^([A-Za-z]+[\w-]*\.?)+@([\w-]+\.)+[A-Za-z]{2,4}$/;
	if(!e.value || !e.value.match(ex)) {
      return 'You must enter a valid email address';
    } else {
      return true;
    }		
  }
  if(id != 'ContactMessage') {
	if(!e.value || e.value == '') {
	  return 'The \'' + name + '\' field can\'t be blank';
	}
  } else {
	if((!e.innerHTML || !e.innerHTML == '') && (!e.value || e.value == '')) {
	  return 'The \'' + name + '\' field can\'t be blank';
	}
  }
  return true;
}



/********************************************************************
 * Validate Form
 Add to form tag:  onsubmit="return checkdata();"
 *******************************************************************/

function checkContactForm() {
  var f = document.groupSalesContact;
  var errors;
  var errormsg = 'The Following errors have occurred:\n\n';
  //for(var i = 0; i < f.elements.length; i++) { if(fcheck(f.elements[i].id) == false) { return false; } }
  for(var i = 0; i < f.elements.length; i++) {
	if(f.elements[i].id && f.elements[i].id != '' && f.elements[i].id != 'ContactCity') {
	  if(fcheck(f.elements[i].id) != true) {
		errors = 1;
		errormsg += fcheck(f.elements[i].id) + '\n\r';
	  }
	}
  }
  if(errors == 1) { alert(errormsg); return false; }
  return true;
}

 
function checkdata(id) {	
  var errormessage = "The following errors have occured:\n\r\n";
  var noerror = 1;

  switch(id) {
	case 'ScheduleEmail':
	  var email = document.getElementById(id);
	  if(echeck(email.value) == false) {
		errormessage += "Please enter a valid email address\r\n";
		noerror = 0;
	  }
	  break;
	case 'SchedulePhone':
	  var phone = document.getElementById(id);
	  if(pcheck(phone.value) == false) {
		errormessage += "Please enter a valid cell phone number\r\n";
		noerror = 0;
	  }
	  break;
	default:
	  if(fcheck(id) != true) {
		//errormessage += fcheck(id);
		errormessage += "error";
		noerror = 0;
	  }
  }

    // --- check if errors occurred ---
  if (noerror == 0) {
	alert(errormessage);
	return false;
  } else { 
    return true;
	uploadInProgress();
  }
}