/*
* Global dom on-loaded event. Triggers functionality based on presece of DOM elements. Ajaxy stuff is assigned upon doc loading here.
* - Creates the modal window for the website login
*/


$.noConflict();
jQuery(document).ready(function($) {
  $('#date').datepicker({ minDate: new Date(), altField: '#massage-date' });
  
});
// Code that uses other library's $ can follow here.


document.observe("dom:loaded", function() {

//	if ($('login_link')) bindLoginLink();	// Assign the modal-window functionality for the login_link in the header
	
	// create auto-calculate function for one-time transactions
	// or Create auto-calculate function for user-selection of pacakages
	if ($('tbl_order_total')) {
		bindDynamicOrderTotalling();
	}
	
	if ($('salesTaxFieldContainer')) {
		bindDynamicOrderTotalling();
	}
	
	if ($('ccExample')) bindCCExampleLink();	// Assigns modal functionality for the credit card example

  bindContentTeasers();

  if ($('home-rotator')) activateHomeBanners();

});

/*
************************************************************
*/

// MEMBER SIGN UP FORM LOGIC 

// Returns the form's authenticity token for rails processing
function getAuthToken() {
	var node = document.getElementsByName('authenticity_token');
	return $(node[0]).getValue();
}

/**
 * Used by in-field ajax calls to handle responses from the server. Will modify the dom based on whether or not
 * an error was received. If fails, a div.formError is posted. If successful, a check box indicator.
 * @param	t					the Prototype ajax transport that was returned by the ajax request.
 * @param observee	the element which originally triggered the event  
 */
function ajaxValidationCallback(t, observee) {
	var fld = $(observee);
	var errorFlags = fld.up().select('.formError');
	var errorMsgExists = errorFlags.length > 0;
	var isValid = false;
	errorFlags.each(function(s) {
		$(s).remove();
	});

	if (t == "") {
		// no errors returned
		isValid = true;
		//if (errorMsgExists) fld.up().next('.formError').remove();	// remove the error from dom
	} else {
		isValid = false;
		// found errors
		//if (errorMsgExists) fld.up().next('.formError').remove();
		var msgContainer = new Element('div', { 'class' : 'formError'}).update(t);
		fld.insert({'after' : msgContainer});
	}
	
	insertFieldIcon(fld, isValid);
}

/**
 * Attaches the field icon
 */
function insertFieldIcon(fld, isValid) {
	var fld = $(fld);
	var errorFlags = fld.up().select('.validatorIcon');
	errorFlags.each(function(s) {
		$(s).remove();
	});
	
	var containerClassName = "validatorIcon " + ((isValid) ? 'validateSuccess' : 'validateFailure');
	var iconContainer = new Element('div', { 'class' : containerClassName });
	if(isValid) {
		iconContainer.update( new Element('img', { 'src' : '/images/icon_success.gif', 'width' : '15', 'height' : '15' }));
		fld.insert({'after' : iconContainer });
	} else {
		iconContainer.update( new Element('img', { 'src' : '/images/icon_failure.gif', 'width' : '15', 'height' : '15' }));
		fld.insert({'after' : iconContainer });
	}
}


/**
 * Checks a text input and determines if the date is valid: mm/dd/yyyy
 */
function validateDateField(fld) {
	var fld = $(fld);
	var regDate = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
	var isValid = fld.value.match(regDate)
	var errorFlags = fld.up().select('.formError');
	var errorMsgExists = (errorFlags.length > 0);
	errorFlags.each(function(s) {
		$(s).remove();
	});

	if (!isValid && !errorMsgExists) {
		var msgContainer = new Element('div', { 'class' : 'formError'}).update("Please ensure date of birth is in mm/dd/yy format");
		fld.insert({'after' : msgContainer});
	}
	insertFieldIcon(fld, isValid);
}

/**
 * Confirms that the password confirmation field matches the first password field
 */ 
function confirmMatchingPassword(fld) {
	var fld = $(fld);
	var passfield = fld.id.replace("_confirmation", '');
	var fieldsMatch = $(passfield).value == $(fld).value;
	var errorMsgExists = (fld.up().select('.formError').length > 0);
	
	if (fieldsMatch) {
		if (errorMsgExists) {
			fld.up().select('.formError')[0].remove();
		}
	} else {
		if (!errorMsgExists) {
			var msgContainer = new Element('div', { 'class' : 'formError'}).update("Passwords do not match");
			$(fld).insert({'after' : msgContainer});
		}
	}
}

/**
 * Refreshes the layout of the form through javascript
 */
function nextStepButtonPressed( activeIndex, nextIndex ) {
	var lastStep = "signUpStep" + parseInt(activeIndex);
	var nextStep = "signUpStep" + parseInt(nextIndex);
	$(lastStep).hide();
	$(nextStep).show();
}

/**
 * Called when the previous button is pressed
 */
function prevStepButtonPressed( activeIndex, nextIndex) {
	nextStepButtonPressed(activeIndex, nextIndex);
}


/**
 * Validates a step
 */
function validateStep(stepNum) {
	var stepValid = false;
	if (stepNum == 1) {
		var requiredSuccesses = 7;
		var successes = $('signUpStep1').select('div.validateSuccess');
		if (successes.length == requiredSuccesses) {
			stepValid = true;
		} else {
			stepValid = false;
		}
	}
	
	if (stepValid) {
		//console.log("Passed validation");
	} else {
		//console.warn("not valid");
	}
}



/**
* Login control logic
* - Provides event handling for logging in via ajax
*/

	//  Objects for tracking js-state of page components
	var expandableAnimationInProgress = false;
	var loginModal = null;
	var loginModalState = {};		// used for storing state information about the login modal window

	// Assigsn the login link behavior for the pulic website. This will trigger a modal window to open
	// when the user has click on the MyMode link
	function bindLoginLink() {
		$('login_link').writeAttribute('href', '#login'); // rewrite for accessibility
		loginModal = createSimpleModal($('login_link'), null, onLoginWindowOpenStart);
	}
	
	// Event handler for window opening. Populates the modal contents with an ajax response
	function onLoginWindowOpenStart() {
		// this is a hack to prevent the beforeOpen event hander form being called twice
		if(!loginModalState.receivedOpen) {
			loginModalState.receivedOpen = true;
			
			url = '/login';
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(t) {
					loginModal.container.insert( t.responseText)
				}
			});
		}
	}
// END login control logic

/*
* Used to bind the credit card examples
* - shows tool tips for either Visa/Mastercard and Discover
*/
	
	// Enables the cc popup
	function bindCCExampleLink() {
		createSimpleModal($('ccAmex'), '<img src="/images/cv-amex.jpg" width="272" height="193" />');
		createSimpleModal($('ccOther'), '<img src="/images/cv-card.jpg" width="269" height="186" />');		
	}
	
	/**
	* Creates a static modal window - non-ajax content 
	* @param		el				the html element that will trigger the modal window
	* @param		content		the content of the modal window
	* @param		beforeOpen			trigger before opening
	* @param		afterOpen				trigger after opening
	* @returns	Control.Modal		returns a LivePipe instance
	*/
	function createSimpleModal(el, content, beforeOpen, afterOpen) {
		// For more info on Control.Window library, see http://livepipe.net/control/window
		var modal = new Control.Modal(el, { 
												overlayOpacity: 0.75,
												className: 'modal',
												width: '300',
												fade: true,
												beforeOpen: beforeOpen,
												afterOpen: afterOpen
		});
		
		if (content) modal.container.insert(content);
		return modal;
	}
	
	

/*
* Press releases functionality
* - toggles visibility and animation for the press releases
*/
	
	function initToggleContainers()
	{
		if (expandableAnimationInProgress) return;
		expandableAnimationInProgress = true;
		var imgArrows = $$('div.expandable img.arrow');
		var titles = $$('div.expandable div.expandable-title h2 a');
		var viewLinks = $$('div.expandable a.expandable-view-more');
		initToggleContainer_arrows(imgArrows);
		initToggleContainer_titles(titles);
		initToggleContainer_viewLink(viewLinks);
	}
	
	function initToggleContainer_viewLink(links) {
		for(var i=0; i < links.length; i++) {
			var link = $(links[i]);
			link.onclick = function() { return false; }
			link.observe("click", function(e) {
				var groupId = $(this).up().up().readAttribute('id');
				togglePressRelease(groupId);
			});
		}
	}
	
	
	function initToggleContainer_arrows(arrows) {
		for(var i = 0; i < arrows.length; i++) {
			var arrow = $(arrows[i]);
			arrow.observe("click", function(e) {
				var groupId = $(this).up().up().readAttribute('id');
				togglePressRelease(groupId);
			});
		}
	}
	
	function initToggleContainer_titles(titles) {
		for(var i = 0; i < titles.length; i++) {
			var title = $(titles[i]);
			title.observe("click", function(e) {
				var groupId = $(this).up().up().up().readAttribute('id');
				togglePressRelease(groupId);
			});
		}
	}
	
	// Toggles the visibility of the press release block
	function togglePressRelease(caller_id) {
		var titleDiv = $(caller_id);
		var isTitleSelected = titleDiv.select('div.expandable-title-selected').length;
		if(isTitleSelected) {
			hideToggleContent(caller_id);
		} else {
			showToggleContent(caller_id);
		}
	}
	
	function showToggleContent(toggleContainerId)
	{
		var toggleContainer = $(toggleContainerId);
		var imgArrow = toggleContainer.down('img.arrow');
		var imgArrow_off = '/images/toggle-arrow-down.gif';
		var link = toggleContainer.down('.expandable-view-more');
		if (link) link.innerHTML = 'hide';
		toggleContainer.down('div.expandable-title').addClassName('expandable-title-selected');
		toggleContainer.down('div.expandable-title').removeClassName('expandable-title');
		showDiv( $(toggleContainerId + "_content") );
		$(imgArrow).writeAttribute('src', imgArrow_off);
	}
	
	function hideToggleContent(toggleContainerId)
	{
		var toggleContainer = $(toggleContainerId);
		var imgArrow =  toggleContainer.down('img.arrow');
		var imgArrow_on = '/images/toggle-arrow-right.gif';
		var link = toggleContainer.down('.expandable-view-more');
		if (link) link.innerHTML = 'read more';
		toggleContainer.down('div.expandable-title-selected').addClassName('expandable-title');
		toggleContainer.down('div.expandable-title-selected').removeClassName('expandable-title-selected');
		hideDiv( $(toggleContainerId + "_content") );

		$(imgArrow).writeAttribute('src', imgArrow_on);
	}

	function showDiv(divId) {
		Effect.BlindDown(divId, { duration: 0.15, afterFinish: clearReleaseInterval});
	}

	function hideDiv(divId) {
		Effect.BlindUp(divId, { duration: 0.15, afterFinish: clearReleaseInterval});
	}

	// Releases the block on press release animations
	function clearReleaseInterval() {
		expandableAnimationInProgress = false;
	}
// END press release logic


/*
* Order calculation logic
* - responsible for creating sales tax, and totals from a base price
* - responsible for tabulating order totals when a user selects different fitness packages
*/
	var orderData = {};
	
	// Creates listeners for user behavior occurring during an order process
	function bindDynamicOrderTotalling() {
		// Creates dynamic totalling for package selection
		if($('packages')) {
			// Initializes page elements when user has not yet selected an element
			if (!orderData.selectedId) {
				orderData.selectedId = findSelectedPackageId();
				recalculatePackageTotals(orderData.selectedId);
			}

			// Assign the behavior to the package radio buttons
			Event.addBehavior({
				'input.radPackage:click' : function(e) {
					// Send a request to the packages controller to query price and update form elements
					orderData.selectedId = findSelectedPackageId();
					recalculatePackageTotals(orderData.selectedId);
				}
			});
		}

		// creates dynamic totalling for 3 text boxes, responding to changes in 'base_price'
		if($('salesTaxFieldContainer')) {
			
			Event.addBehavior({
				'input.tfldBasePrice:blur' : function(e) {
					orderData.basePrice = $('tfldBasePrice').value;
					refreshTaxAndTotal(orderData.basePrice);
				}
			});
		}
	}
	
	// Determines the selected package form the page's radio button attributes.
	// This function will look for a table with th ID of packages and search from there.
	function findSelectedPackageId() {
		container = $('packages');
		var foundId = null;
		var chk = container.down('input:checked');
		foundId = chk.value;

		if(!foundId) {
			//console.error("Could not determine selected package");
			return;
		} else {
			return foundId;
		}
	}
	
	// Creates the request to the server to determine package pricing, updates DOM
	function recalculatePackageTotals(packageId) {
		if (!packageId) {
			//console.error("recalculatePackageTotals() requires a package ID.");
			return;
		}
		
		var packages_url = "/packages/" + packageId + '.json';
		//console.log("Find url " + packages_url);
		req = new Ajax.Request(packages_url, {
			contentType: 'application/json', 
			method : 'get',
			
			onCreate: function() {
				$('imgTotalLoader').show();
			},
			
			onSuccess: function(t) {
				$('imgTotalLoader').hide();
				$('tdBasePrice').innerHTML = monitizeFromCents(t.responseJSON.package.base_price);
				$('tdTax').innerHTML = monitizeFromCents(t.responseJSON.package.sales_tax);
				['tdTotal', 'strTotal'].each(function(el) {
					$(el).innerHTML = monitizeFromCents(t.responseJSON.package.total_price);
				});
			}
		});
	}

	// Creates a formatted currency string from cents, e.g. 9900 -> $ 99.00
	function monitizeFromCents(cents) {
		return "$" + (cents/100).toFixed(2);
	}
	
	// Refreshes the sales tax value and total value from a specified basePrice amount
	// @param		basePrice				the subtotal or before tax value
	// @param		tfldSalesTaxId		the ID of the sales tax text field element
	// @param		tfldTotalId			the ID of the total text field element
	function refreshTaxAndTotal(basePrice, tfldSalesTaxId, tfldTotalId) {
		var tfldSalesTax = $(tfldSalesTaxId) || $('tfldSalesTax');
		var tfldTotal = $(tfldTotalId) || $('tfldTotal');
		if(!tfldSalesTax || !tfldTotal) {
			//console.error("Must specify valid sales tax and total fields");
		}
		
		var orders_url = "/admin/orders/calculate_total";
		
		req = new Ajax.Request(orders_url, {
			contentType: "application/json",
			method : "get",
			parameters : { "order[base_price]" : basePrice },
			
			onCreate: function() {
				$('imgTotalLoader').show();
			},
			
			onSuccess: function(t) {
				var order = t.responseJSON.order;
				tfldSalesTax.value = order.order_tax.toFixed(2);
				tfldTotal.value = order.total_price.toFixed(2);
				$('imgTotalLoader').hide();
			}
			
		});
	}
	
	/**
	 * This function is used to trap the enter key from form submission. It is used in the multipart customer sign up form
	 */
	function trapEnterKey() {
		Event.observe(document, 'keypress', function(event){ 
			if(event.keyCode == Event.KEY_RETURN) {
				Event.stop(event);
			}
		});
	}
	
	/**
	 * Initializes the sign up buttons at the top of the signup page form. Pressing one of these numbers will cause the form to hide other steps
	 * while showing the currently selected step number
	 */
	function initMemberSignUpStepButtons() {
		
	}
	
	/**
	 * Renders a sign up step visible, disabling other steps currently visible
	 */
	function showMemberSignUpStep(stepNumber) {
		divIds = [];
		for(var i = 1; i <= 4; i++) {
			var div = "signUpStep" + parseInt(i);
			if (i != stepNumber) {
				$(div).hide();
			}			
			divIds.push(div);
		}
		var newDiv = divIds[ stepNumber - 1];
		$(newDiv).show();
	}
	
	/**
	 * Image loader methods
	 */
	utils = {};
	
	utils.addEventListener = function(element, type, expression, bubbling) {
		bubbling = bubbling || false;
	  if(window.addEventListener)	{ // Standard
	    element.addEventListener(type, expression, bubbling);
	    return true;
	  } else if(window.attachEvent) { // IE
	    element.attachEvent('on' + type, expression);
	    return true;
	  } else return false;
	}
	
	
	ImageLoader = function(url) {
		this.url = url;
		this.image = null;
		this.loadEvent = null;
	};
	
	ImageLoader.prototype = {
		load: function() {
			this.image = document.createElement('img');
			var url = this.url;
			var image = this.image;
			var loadEvent = this.loadEvent;
			utils.addEventListener(this.image, 'load', function(e){
			  if(loadEvent != null){
			    loadEvent(url, image);
			  }
			}, false);
			this.image.src = this.url;

		},
		getImage:function() {
			return this.image;
		}
	}
	
	/**
	 * Photo viewer gallery widget
	 */
	var PhotoViewer = Class.create({
		initialize : function(viewer_id) {
			this.viewer_id = viewer_id;
			this._activeIndex = null;
			this._THUMB_WIDTH = 83;
			this._THUMB_PADDING = 7;
			this._THUMB_STROKE_WIDTH = 2;
			this._slides = $(this.viewer_id).select('div.slide');
			this.carousel = new Carousel($(this.viewer_id).down('#carousel-content'), 
																	 this._slides, 
																	 $$('a.carousel-control'),
																	 { 
																			visibleSlides : 4,
																			duration: 0.25
																	 });
			
			var numSlides = $(this.viewer_id).select('div.slide').length;
			var slideContainerWidth = (this._THUMB_WIDTH * numSlides) + (this._THUMB_PADDING * numSlides) + (this._THUMB_WIDTH - this._THUMB_PADDING * 2) + "px";
			$(this.viewer_id).down('div.inner').setStyle({width: slideContainerWidth});
			
			this.bindThumbLinks();
			this.selectThumb(0);
		},
		
		bindThumbLinks : function()
		{
			var scope = this;
			for(var i=0; i < this._slides.length; i++) {
				var link = $(this._slides[i]).down('a');
				link.onclick = function() {	return false;	}
				link.observe('click', function(event) {
					scope.onThumbClick(event.target);
				});
			}
		},
		
		onThumbClick : function(el)
		{
			var link = $(el);
			var slide = link.up().up();
			var slideIndex = this.getSlideIndexFromSlide( $(slide));
			if (slideIndex != null) this.selectThumb(slideIndex);
		},
		
		getSlideIndexFromSlide : function(slideHtml)
		{
			for (var i=0; i < this._slides.length; i++) {
				var slide = $(this._slides[i]);
				if (slide == slideHtml) return i;
			}
			return null;
		},
		
		selectThumb : function(index)
		{
			if (index != this._activeIndex) {
				var activeThumb = $(this._slides[index]);
				var fullImageUrl = activeThumb.down('a').href;
				var img = activeThumb.down('img');
				var imgTitle = img.alt;
				
				this.deselectThumbs();
				img.addClassName('selected');
				this._activeIndex = index;
				this.showMainImage(fullImageUrl);
				this.fillCaption(imgTitle);
			}
		},
		
		showMainImage : function(imageUrl)
		{
			var scope = this;
			this.showPreloader();
			var imgHtml = new Element('img', { 'src' : imageUrl, 'width' : 463, 'height' : 308 });
			var loader = new ImageLoader(imageUrl);
			loader.loadEvent = function(url, image) {
				$('main-photo-container').innerHTML = "";
				$('main-photo-container').insert(imgHtml);
				scope.hidePreloader();
			}
			loader.load();
		},
		
		showPreloader : function()
		{
			$('loadScreen').show();
		},
		
		hidePreloader : function()
		{
			//$('loadScreen').hide();
			new Effect.Fade('loadScreen', { duration: 0.3 });
		},
		
		deselectThumbs : function()
		{
			var selected = $(this.viewer_id).select('img.selected');
			for (var i = 0; i < selected.length; i++) {
				var img = $(selected[i]);
				img.removeClassName('selected');
			}
		},
		
		fillCaption : function(text)
		{
			$('photo-caption').innerHTML = text;
		}
	});
	
	/**
	 * A cycleable widget for viewing parter logos
	 */
	var PartnerWidget = Class.create({
		initialize : function(widget_id) {
			this.LOGO_WIDTH = 150;
			this.widget_id = widget_id;
			this._activeIndex = null;
			this._logos = $(this.widget_id).select('a.logo');
			this.carousel = new Carousel( $(this.widget_id).down('#partner-logo-view'),
																		this._logos,
																		$(this.widget_id).select('a.carousel-control'),
																		{
																			auto: true,
																			frequency: 5,
																			circular: true,
																			visibleSlides: 1,
																			duration: 0.4
																		});
			this.resizeLogoMask();
		},
		
		resizeLogoMask : function()
		{
			var numLogos = this._logos.length;
			var logoContainerWidth = this.LOGO_WIDTH * numLogos + 'px';
			$(this.widget_id).down('div.inner').setStyle({ width: logoContainerWidth});
		}
	});
	
	
	// Helpers
	//--------------------------------------------------------------------------
	var $_GET = {};
	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
	    function decode(s) {
	        return decodeURIComponent(s.split("+").join(" "));
	    }

	    $_GET[decode(arguments[1])] = decode(arguments[2]);
	});

function bindContentTeasers() {
  $$('.section-teaser').each(function(el){
    el.next().hide();
    el.observe('click', showTeasedContent);
  });

  $$('.arrow-list a').each(function(el){
    var target = el.readAttribute('href').replace('#', '');

    el.observe('click', function(){bindNameLink(target)});
  });
}

function showTeasedContent() {
  this.next().show();
  this.stopObserving('click', showTeasedContent);
  this.addClassName('revealed');
  this.observe('click', hideTeasedContent);
}

function hideTeasedContent() {
  this.next().hide();
  this.stopObserving('click', hideTeasedContent);
  this.removeClassName('revealed')
  this.observe('click', showTeasedContent);
}

function bindNameLink(target) {
  fireEvent($(target).next(), 'click');
}

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

var bannerTokens = ['yoga', 'massage', 'bootcamp', 'training'];
var bannerUrls = ['https://modeoffitness.myvolo.ca/club/store/store.jsp?category_id=26', '/seattle/massage/index', '/seattle/mode/bootcamp', '/seattle/training/index'];
var bannerIndex = 0;

function activateHomeBanners() {
  setInterval("rotateHomeBanner()", 5000);
}

function rotateHomeBanner() {
  nextIndex = nextBannerIndex();
  nextToken = bannerTokens[nextIndex];
  nextImage = '/images/banner-' + nextToken + '.jpg'
  $('home-rotator').setStyle({backgroundImage: 'url(' + nextImage + ')'})
  $('banner-button').setAttribute('href', bannerUrls[nextIndex]);
}

function nextBannerIndex() {
  if (bannerIndex == bannerTokens.length - 1){
    bannerIndex = 0
  } else {
    bannerIndex++;
  }
  return bannerIndex;
}

