/**
 * @author chicks
 */
var $j = jQuery.noConflict();
			
$j(function() {
	$j('#view-tabs li a').click(function() {
		if($j(this).parent().hasClass('locked')) {
			return false;
		}
		
		//Show the content
		$j('.view-tabs-content:visible').hide();
		$j($j(this).attr('href')).show();
		
		//Switch the active tab style
		$j(this).parent().siblings('.active').removeClass('active');
		$j(this).parent().addClass('active');
		
		return false;
	});
	
	/*
	$j('.add-to-cart-button').click(function() {
		$j(this).attr('disabled', 'disabled');
		$j(this).parents('form').submit();
	});
	*/
	
	$j('.place-order-button').click(function() {
		$j(this).attr('disabled', 'disabled');
		$j(this).parents('form').submit();
	});
	
	/*
	 * Calendar Events
	 */
	if(BBNutcracker.config.active) {
		BBNutcracker.init();
	}
	
	if(BBShoppingCart.config.active) {
		BBShoppingCart.init();
	}
	
	if(BBModal.config.active) {
		BBModal.init();
	}
	
	if(BBSpecialEvents.config.active) {
		BBSpecialEvents.init();
	}
	
});

Array.prototype.contains = function (element) {
	for(var i = 0; i < this.length; i++) {
		if(this[i] === element) {
			return true;
		}
	}
	return false;
}

String.prototype.isInt = function() {
	var i = parseInt(this);

	if (isNaN(i))
		return false;

	i = i.toString();
	if (i != this)
		return false;

	return true;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.isEmpty = function() {
	return (this.length === 0);
}


function getCurrentSectionTitle() {
	var headerTitle = $j('#main .nav h3');
	
	if (headerTitle.length == 1) {
		return headerTitle.text().replace("&", "**amp**");	
	}
	
	return "";
}

function LOG(message) {
	if(typeof console == 'object') {
		console.log(message);
	}
}

/*
 * Checkout JS.
 */
BBCheckout = {}

/*
 * Set via templates
 * 
 * Possible params:
 * - containsTickets <boolean>
 * - ticketShippable <boolean>
 * - containsGiftShopItems <boolean>
 */
BBCheckout.config = {
		holdingTickets: false,
		shippingMethod: '',
		shippingMethodId: 0
}

BBCheckout.init = function() {
	//console.log("BBCheckout.init...");
	//console.log("hold inputs: " + $j('input[name$="holdingTickets"]').length);
	$j('input[name$="shippingMethod"]').click(function() {
		//LOG("selected a new shipping method!");
		var methodText = $j(this).parent().text();
		
		if (methodText.indexOf("Mail") > 0) {
			BBCheckout.config.shippingMethod = "Mail";
		} else if (methodText.indexOf("Print At Home") > 0) {
			BBCheckout.config.shippingMethod = "Print At Home";
		} else if (methodText.indexOf("Will Call") > 0) {
			BBCheckout.config.shippingMethod = "Will Call";
		}
		
		LOG("selected method is: " + BBCheckout.config.shippingMethod);
		
		var elemId = $j(this).attr('id')
		var methodId = elemId.substring(elemId.indexOf('_') + 1);
		
		LOG("selected method ID is: " + methodId);
		
		if(BBCheckout.config.shippingMethod == "Mail") {
			BBCheckout.showAddressPane();
		} else {
			BBCheckout.hideAddressPane();
		}
		
	});
	
	$j('input[name$="holdingTickets"]').click(function() {
		//console.log("holdTickets CLICK");
		var holdingTickets = $j('input[name$="holdingTickets"]:checked').val();
		
		//console.log("holdingTickets Input value: " + holdingTickets);
		
		if(holdingTickets == "yes") {
			BBCheckout.config.holdingTickets = true;
		} else {
			BBCheckout.config.holdingTickets = false;
		}
		
		BBCheckout.updateShippingUI();
	});
	
	$j('input[name="address"]:not(input[value="newAddressRadio"]):not(input[value="newBillingAddressRadio"])').click(function() {
		$j('#newAddressForm').hide();
	});
	
	$j('#newAddressRadio').click(function() {
		$j('#newAddressForm').show();
	});
	
	$j('#newBillingAddressRadio').click(function() {
		$j('#newAddressForm').show();
	});
	
}

BBCheckout.showAddressPane = function() {
	$j('#selectAddress').show();
}

BBCheckout.hideAddressPane = function() {
	$j('#selectAddress').hide();
}

BBCheckout.updateShippingUI = function() {
	//console.log("BBCheckout.updateShippingUI...");
	
	var holdingTicketsOptionExists = ($j('input[name$="holdingTickets"]').length > 0);
	//console.log("holdingTicketsOptionExists: " + holdingTicketsOptionExists);
	
	if(holdingTicketsOptionExists) {
		//console.log("holdingTickets: " + BBCheckout.config.holdingTickets);
		
		var showAddressOptions = true;
		
		if(BBCheckout.config.holdingTickets && !BBCheckout.config.containsGiftShopItems) {
			showAddressOptions = false;
		}
		
		//console.log("showing address form: " + showAddressOptions);
		
		if(showAddressOptions) {
			$j('#selectAddress').show();
		} else {
			$j('#selectAddress').hide();
		}
	}
	
}

/*
 * Nutcracker Landing Page JS
 */

 BBNutcracker = {}
 BBNutcracker.config = {
 	active: false,
 	performances: new Array(),
 	baseUrl: '/'
 }
 
 BBNutcracker.init = function() {
 	//console.time(1);
 	//console.log('Building Calendar...');
 	//console.log('performances: ' + BBNutcracker.config.performances);
 	
 	$j('#nutcracker .popup .modal-close-button').live('click', function() {
		$j(this).parent().hide();
	});
	
	$j('#nutcracker #ballet-details .calendar-row a').live('click', function() {
		//moveCalendarPopup($j(this));
		BBNutcracker.showPerformanceDetails($j(this));
		return false;
	});
	
	var months = new Array();
	months[10] = "NOV";
	months[11] = "DEC";
	
	BBNutcracker.config.months = months;
	
 	BBNutcracker.loadCalendar();
 	BBNutcracker.injectPerformances();
 	
 	//console.log("Calendar loaded in: ");
 	//console.timeEnd(1);
 }
 
 BBNutcracker.loadCalendar = function() {
 	var startDate = new Date();
 	var endDate = new Date();
 	
 	startDate.setTime(BBNutcracker.config.startDate);
 	endDate.setTime(BBNutcracker.config.endDate);
 	endDate.setDate(endDate.getDate() + 1); //bump it up an extra day so it's included in calendar
 	
 	startDay = BBNutcracker.getModifiedDay(startDate);
 	//console.log("startDay: " + startDay);
 	
 	var currDate = startDate;
 	var numDays = 0;
 	var prevRow = $j('#nutcracker-calendar');
 	var currRow = BBNutcracker.getHTMLCalendarRow();
 	var curMonth = -1;
 	
 	while (currDate.getTime() <= endDate.getTime()) {
 		//console.log(currDate + '('+ currDate.getTime() +' <= '+ endDate.getTime() +')');
 		
 		/*
 		if (currRow.find('li').length == 7) {
 			prevRow.after(currRow);
 			prevRow = currRow;
 			currRow = BBNutcracker.getHTMLCalendarRow();
 			//console.log('created new row');
 		}
 		*/
 		
 		if(numDays == 0) {
 			for (var i = 0; i < startDay; i++) {
 				currRow.append('<li class="empty"></li>');
 			}
 		}
 		
 		var month = '';
 		if(curMonth != currDate.getMonth()) {
 			curMonth = currDate.getMonth();
 			month = BBNutcracker.config.months[curMonth];
 		}
 		
		currRow.append('<li>' +
		 					'<div class="cell">' +
			 					'<div class="month">'+ month +'</div>' +
			 					'<div class="date">'+ currDate.getDate() +'</div>' +
		 					'</div>' +
						'</li>');
		
		var dateStr = BBNutcracker.getDateStr(currDate);
		
		currRow.find('li:last').data('key', dateStr);
 
 		
 		numDays += 1;
 		currDate.setDate(currDate.getDate() + 1);
 		
 		if (currRow.find('li').length == 7) {
 			prevRow.after(currRow);
 			prevRow = currRow;
 			currRow = BBNutcracker.getHTMLCalendarRow();
 			//console.log('created new row');
 		}
 	}
 	prevRow.after(currRow);
 	//console.log("numDays: " + numDays);
 }
 
 BBNutcracker.injectPerformances = function() { 	
 	for(var i = 0; i < BBNutcracker.config.performances.length; i++) {
 		BBNutcracker.injectPerformance(BBNutcracker.config.performances[i]);
 	}
 }
 
 BBNutcracker.injectPerformance = function(data) {
 	var cells = $j('.calendar-row li');
 	cells.each(function() {
 		if($j(this).data('key') === data.key) {
 			var link;
 			
 			LOG(data.dateStr + ": " + data.displayable);
 			
 			if(data.displayable) {
 				link = $j('<a href="'+ BBNutcracker.config.baseUrl + '/' + data.url +'">'+ data.timeStr +'</a><br />');
 			} else {
 				link = $j('<span>' + data.timeStr +'</span><br />');
 				LOG(link);
 			}
			
			$j(this).find('.cell').append(link);

 			
 			
 		}
 	});
 }
 
 BBNutcracker.getHTMLCalendarRow = function() {
 	return $j('<ul class="calendar-row"></ul>');
 }
 
 BBNutcracker.getDateStr = function(date) {
 	return date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
 }
 
 BBNutcracker.getModifiedDay = function(date) {
 	day = date.getDay();
 	if(day > 0) {
 		day -= 1;
 	} else {
 		day = 6;	
 	}
 	return day;
 }
 
 BBNutcracker.addPerformance = function(dateTime, url, fullDateStr, timeStr, active) { 
 	var perfDate = new Date();
 	perfDate.setTime(dateTime);
 	var dateStr = BBNutcracker.getDateStr(perfDate);
 	
 	BBNutcracker.config.performances.push({
 		key: dateStr,
 		url: url,
 		dateStr: fullDateStr,
 		timeStr: timeStr,
 		displayable: active
 	});
 	
 }
 
 BBNutcracker.showPerformanceDetails = function(link) {
	var popup = $j('#nutcracker .popup');
	popup.hide();
	
	var css = {
		"position": "absolute",
		"top": link.position().top + 23,
		"left": link.position().left - 151,
		"z-index": "2",
		"direction": "ltr"
	};
	popup.css(css);
	popup.appendTo(link.parent());
	
	var perfDetails = link.data('perfDetails');
	popup.find('p:first').html(perfDetails.dateStr + '<br />' + perfDetails.timeStr);
	popup.find('a:first').attr('href', BBNutcracker.config.baseUrl + '/' + perfDetails.url);
	
	popup.fadeIn();
 }

 BBShoppingCart = {}
 BBShoppingCart.config = {
 	active: false,
 	nextExpiration: 0,
 	intervalId: 0,
 	messageDelay: 30000
 }
 
 BBShoppingCart.init = function() {
 	if(BBShoppingCart.config.nextExpiration > 0) {
 		BBShoppingCart.config.nextExpiration += 5;
 		BBShoppingCart.startCountDown();
 	}
 	
 	$j('a[href^="remove-cart-item.ep"]').click(function(){
 		$j(this).hide();
 		$j(this).after('Please wait...');
 		setTimeout(BBShoppingCart.showRemoveCartItemLink, 5000);
 	});
 }
 
 BBShoppingCart.showRemoveCartItemLink = function() {
 	$j(this).fadeIn(500)
 }
 
 BBShoppingCart.startCountDown = function() {
 	BBShoppingCart.config.intervalId = setInterval(BBShoppingCart.updateExpStatus, 1000);
 	
 }
 
 BBShoppingCart.updateExpStatus = function() {
 	BBShoppingCart.config.nextExpiration -= 1;
 	var seconds = BBShoppingCart.config.nextExpiration;
 	
 	//console.log("Expiration in: " + seconds + " seconds.");
 	
 	if(seconds <= 0) {
 		clearInterval(BBShoppingCart.config.intervalId);
 		location.reload(true);
 	}
 	
 	if(seconds == 60 || seconds == 120 || seconds == 180 || seconds == 240) {
 		BBShoppingCart.showExpirationWarning(seconds / 60);
 	}
 }
 
 BBShoppingCart.showExpirationWarning = function(minUntilExp) {
 	var warningDiv = $j('#expired-ticket-warning');
 	warningDiv.hide();
 	warningDiv.find('.warning-text').html("There are tickets in your shopping cart that are going to expire in "+ minUntilExp +" minutes. Please proceed to checkout if you would like to purchase them.");
 	warningDiv.show();
 	warningDiv.fadeOut(BBShoppingCart.config.messageDelay);
 }
 
 /*
  * BB Modal JS
  */
  BBModal = {}
  
  BBModal.config = {
  	active: true
  }
  
  BBModal.init = function() {
  	$j('#sign_id').click(function() {
  		tb_show("","/storefront/modal-sign-in.ep?height=250&width=466", "");
  		return false;
  	});
  	
  	$j('.modal-sign-in-win1').live('click', function() {
  		$j("#sign-in-table-1").show();
    	$j("#sign-in-table-2").hide();
    	$j("#sign-in-table-3").hide();
    	$j("#sign-in-table-1-btn").show();
    	$j("#sign-in-table-2-btn").hide();
    	$j("#sign-in-table-3-btn").hide();
  	});
  	
  	$j('.modal-sign-in-win2').live('click', function() {
  		$j("#sign-in-table-1").hide();
    	$j("#sign-in-table-2").show();
    	$j("#sign-in-table-3").hide();
    	$j("#sign-in-table-1-btn").hide();
    	$j("#sign-in-table-2-btn").show();
    	$j("#sign-in-table-3-btn").hide();
  	});
  	
  	$j('.modal-sign-in-win3').live('click', function() {
  		$j("#sign-in-table-1").hide();
    	$j("#sign-in-table-2").hide();
    	$j("#sign-in-table-3").show();
    	$j("#sign-in-table-1-btn").hide();
    	$j("#sign-in-table-2-btn").hide();
    	$j("#sign-in-table-3-btn").show();
  	});
  }
 
 
BBValidator = {
	messages: { 
		required: "This field is required.",
		invalid: "The contents of this field are invalid.",
		maxlength: "The value of this field is too long."
	}
}

BBValidator.validate = function(form, config) {
	$j(form).find('span.req').remove();
	var valid = true;
	
	for(var i = 0; i < config.length; i++) {
		console.log("checking: " + config[i].field);
		var field = $j(form).find('input[name="'+ config[i].field +'"]');
		for(var idxRules = 0; idxRules < config[i].rules.length; idxRules++) {
			var rule = config[i].rules[idxRules];
			var result;
			console.log("got rule: " + rule + "; checking against value '"+ field.val() +"'");
			
			if(rule.params) {
				result = rule.method(field.val(), rule.params);
			} else {
				result = rule.method(field.val());
			}
			
			console.log("result was: " + result);
			if(!result) {
				field.after('<span class="req">'+ rule.message +'</span>');
				valid = false;
			}
		}
	}
	
	return valid;
}

BBValidator.forms = {}
BBValidator.forms.validateAccountAddressForm = function(form) {
	var config = [
		{ 
			field: "address.firstName", 
			rules: [
				{ method: BBValidator.security, message: BBValidator.messages.invalid },
				{ method: BBValidator.empty, message: BBValidator.messages.required },
				{ method: BBValidator.maxlength, message: BBValidator.messages.maxlength, params: { length: 100 } }
			] 
		},{ 
			field: "address.lastName", 
			rules: [
				{ method: BBValidator.security, message: BBValidator.messages.invalid },
				{ method: BBValidator.empty, message: BBValidator.messages.required },
				{ method: BBValidator.maxlength, message: BBValidator.messages.maxlength, params: { length: 100 } }
			] 
		},{ 
			field: "address.street1", 
			rules: [
				{ method: BBValidator.security, message: BBValidator.messages.invalid },
				{ method: BBValidator.empty, message: BBValidator.messages.required },
				{ method: BBValidator.maxlength, message: BBValidator.messages.maxlength, params: { length: 200 } }
			] 
		},{ 
			field: "address.city", 
			rules: [
				{ method: BBValidator.security, message: BBValidator.messages.invalid },
				{ method: BBValidator.empty, message: BBValidator.messages.required },
				{ method: BBValidator.maxlength, message: BBValidator.messages.maxlength, params: { length: 100 } }
			] 
		},{ 
			field: "address.zip", 
			rules: [
				{ method: BBValidator.security, message: BBValidator.messages.invalid },
				{ method: BBValidator.empty, message: BBValidator.messages.required },
				{ method: BBValidator.maxlength, message: BBValidator.messages.maxlength, params: { length: 50 } }
			] 
		}
	];
	
	return BBValidator.validate(form, config);
}

BBValidator.minlength = function(value, params) {
	var length = params.length;
	
	if (typeof value === "string") {
		return (value.length >= length);
	}
	
	return true;
}

BBValidator.maxlength = function(value, params) {
	var length = params.length;
	
	if (typeof value === "string") {
		return (value.length <= length);
	}
	
	return true;
}

BBValidator.empty = function(value) {
	if (typeof value === "string") {
		return !value.isEmpty();
	}
	
	if (typeof value === "object") {
		return (value.length > 0);
	}
	
	return true;
};

BBValidator.phoneNumber = function(value) {
	var re = new RegExp("^([0-9]|\s|-|\)|\(|\+)*$");
	return value.match(re);
};

BBValidator.security = function(value) {
	if (typeof value === "string") {
		if(!value.isEmpty() && (value.indexOf('>') > 0 || value.indexOf('<') >= 0)) {
			//console.log('security problem!');
			return false;
		}
	}
	
	return true;
};

/*
 * Special Events
 */
BBSpecialEvents = {};

BBSpecialEvents.config = {
	active : false,
	activities : []
};

BBSpecialEvents.init = function() {
	var onOpen = function(hash) { 
		var id = $j(hash.t).attr('id').substring(5);
		var activity = BBSpecialEvents.getEvent(id);
		LOG("id: " + id);
		LOG("activity: " + activity);
		
		hash.w.find('#RSVP-Title').html(activity.activityName);
		hash.w.find("#RSVP-ActivityNo").val(id);
		
		hash.w.show();
	}
	$j('#RSVP-Dialog').jqm({trigger: '.rsvp-small-button', onShow : onOpen});
	$j('#attendees').change(function() {
		var currentCount = $j('#RSVP-AttendeeList input[type="text"]').length;
		var newCount = $j(this).val();
		
		LOG("currentCount: "+ currentCount +", newCount: " + newCount);
		
		if(newCount > currentCount) {
			for(var i = currentCount; i < newCount; i++) {
				$j('#RSVP-AttendeeList').append('<input type="text" name="name'+ i +'" /> <br />');
			}
		}
		
		if(newCount < currentCount) {
			for(var i = currentCount - 1; i >= newCount; i--) {
				$j('#RSVP-AttendeeList input:eq('+ i +')').remove();
			}
		}
	});
}

BBSpecialEvents.addEvent = function(details) {
	this.config.activities.push(details);
};

BBSpecialEvents.getEvent = function(id) {
	for(var i = 0; i < this.config.activities.length; i++) {
		if(this.config.activities[i].activityNo === parseInt(id)) {
			return this.config.activities[i];
		}
	}
}
 