// JavaScript Document
var weekdays     = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var months       = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var today = new Date();
var start= today.getTime();

var carouselImages = ["bg/steak.jpg", "bg/fish.jpg", "bg/desert.jpg", "bg/shrimp.jpg", "bg/frys.jpg"];
var preloadImages = ["ajax-loader.gif", "findatable_rollover.png", "submenu_hover.png", "make_reservation_rollover.png"];
var carouselinterval = 10; //seconds
/*Used in scrollableAreas */
var scrollAreasV = new Array();
var scrollHeightV = 150; //px
var scrollAutomationV = 0;
var scrollAreasH = new Array();
var scrollWidthH = 255; //px
var scrollAutomationH = 0;
/*Used in createAccordion*/
var accordionMenu = new Object();
/*Used in customEvents*/
var customWin;
var customEventFunc;

$(function (){
	if (images_basepath==null) alert("var 'images_basepath' was not set!");
	for (preimage in preloadImages){
		var gfx = preloadImages[preimage];
		preloadImages[preimage] = new Image();
		preloadImages[preimage].src = images_basepath + gfx;
	}
	
	startCarousel();
	makeThickBoxLinks();
	makeRotatingBanners($("#bannerArea"));
	createScrollableAreasV();
	createScrollableAreasH();
	createAccorionMenu($("ul.sub-menu:first"));
	fixAnchors();
	createDropdownCalendars();
	checkFormErrors();
	createTinyMCE();
	customEvents();
	
	
	$("ul.sub-menu:first").find("a").click(function (){ 
		$(this).parent().addClass("selected").siblings().removeClass("selected"); 
		accordionMenu.selected = $(accordionMenu.target).find("li:has(li.selected)");
		$(".transition-fade-out").addClass("ajax-load").children().fadeOut("normal");
	}).parent("li").hover(function (){ $(this).addClass("hover"); }, function (){ $(this).removeClass("hover"); });
	$("ul.sub-menu:first").find("li:has(ul)").addClass("no-hover");
	
	//fade transitions
	$(".transition-fade-in").hide().fadeIn("normal");
});


function customEvents(value){
	if (typeof(value)=="undefined"){
		if ($("#custom").length>0){
			$("#_recurrence").change(function (){
				if ($(this).children("option[label='Custom']").is(":selected")){
					$("#custom").click();
				}else{
					$("#customRecurrenceText").html("");
				}
			});
			$("#custom").click(function (){
				customWin =  window.open(images_basepath.replace('images/', '')+'/lib/js/customEvents.html#'+$("#recurrence").val(),'customWin','width=250,height=320,location=1,menubar=1,resizable=1');
				if (customWin && customWin.top){
					customWin.focus();
				}else{
					$("#customRecurrenceText").html("Please allow your popup blocker to display popups for this site.");
				}
			}).parent().after('<dd id="customRecurrenceText"></dd>');
		}
		var recvalue = $("#recurrence").val();
		if (typeof(recvalue)!='undefined') customEvents(recvalue);
		
		customEventFunc = this.customEvents;
	}else{
		var str = 'every ';
		var found = value.match(/^(\d+)([d|w|m|y])-?([\d+|,]+)?-?([f|s|t|r|l][u|m|t|w|h|f|s])?/i);
		if (found){
			if (parseInt(found[1])>1) str += found[1]+' ';
			switch (found[2]){
				case 'd': str += 'day'; break;
				case 'w': str += 'week'; break;
				case 'm': str += 'month'; break;
				case 'y': str += 'year';  break;
			}			
			if (parseInt(found[1])>1) str +='s';
			
			if (found[4]!=null && found[4].length>0){
				str +=' on the ';
				switch (found[4].substr(0,1)){
					case 'f': str+='first '; break;
					case 's': str+='second '; break;
					case 't': str+='third '; break;
					case 'r': str+='fourth '; break;
					case 'l': str+='last '; break;
				}
				
				temp = {'u':0,'m':1,'t':2,'w':3,'h':4,'f':5,'s':6};
				str += weekdays[temp[found[4].substr(1,1)]];
			}

			if (found[3]!=null && found[3].length>0){
				str+=(found[2]=='y')?' of ':' on ';
				var arr = found[3].split(',');
				for (e in arr){
					if (e!=0) str += (e!=(arr.length-1)?', ': ' and ');
					if (found[2]=='w') str +=weekdays[arr[e]];
					if (found[2]=='m') str +=arr[e]+(arr[e]==1 || arr[e]==31?'st':(arr[e]==2?'nd':(arr[e]==3 || arr[e]==23?'rd':'th')));
					if (found[2]=='y') str +=months[arr[e]];
				}
			}
			
			
			$('#rec_end').removeAttr("disabled");
			$("#customRecurrenceText").html(str);
			$("#recurrence").val(value);
			$("#_recurrence").children("option[label='Custom']").attr("selected", "selected");
		}
	}
}

function createTinyMCE(){
	$('textarea.tinymce').tinymce({
		// Location of TinyMCE script
		script_url : images_basepath+'../lib/js/tiny_mce/tiny_mce.js',

		// General options
		theme : "advanced",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,|,undo,redo,|,link,unlink",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "none",
		theme_advanced_resizing : false
	});

}


function checkFormErrors(){
	$(".zend_form").find("dd:has(.errors)").children("input, textarea, select").addClass("marked-error").focus(function (){$(this).removeClass("marked-error");});
}

function dropdownChange(dropdown, elements){
	for(element in elements){
		if ($(dropdown).val() == ""){
			$("#"+elements[element]).attr('disabled', 'disabled');
		}else{
			$("#"+elements[element]).removeAttr('disabled');
		}
	}
}

function checkboxClick(checkbox, elements){
	for(element in elements){
		if (checkbox.checked){
			$("#"+elements[element]).attr('disabled', 'disabled');
		}else{
			$("#"+elements[element]).removeAttr('disabled');
		}
	}
}

function createDropdownCalendars(){
	$(".popup-calendar").each(function (){
		var caloptions = {
			showOn: 'button',
			buttonImage: images_basepath+'calendar_icon.png',
			buttonImageOnly: true,
			beforeShow:function (input, inst){
				if ($(input).attr('disabled')) $(inst).hide();
				var start_date = $(".popup-calendar-start-date").val();
				if ($(input).hasClass("popup-calendar-end-date")){
					minDate = new Date(start_date);
					if (minDate!="Invalid Date"){
						inst.settings.minDate = minDate;
					}else{
						inst.settings.minDate = today;
					}
				}
				if ($(input).hasClass("popup-calendar-no-contrain")){
					inst.settings.constrainInput = false;
				}
			}
		};
		if ($(this).hasClass("popup-calendar-start-date")) caloptions = $.extend({minDate: today}, caloptions);
		$(this).datepicker(caloptions);
		if ($(this).hasClass("add-repeat-icon")){
			var target = this;
			$(this).after('<img class="repeat-icon" title="Set this event to repeat forever" src="'+images_basepath+'infinity.png" width=16 height=16 alt="Repeat forever" />');
			$(this).parent().find("img.repeat-icon").click(function (){
				if (!$(target).attr("disabled")) $(target).val("Forever");
			});
		}
		
	});
}

function fixAnchors(){
	$("body").find("a").focus(function (){$(this).blur();});
}

function confirmDelete(recurrent){
	if (typeof(recurrent)=='boolean' && recurrent==true){
		return confirm("WARNING! This event is a recurring event. Are you sure you want to delete this recurring event?");
	}else{
		return confirm("Are you sure you want to delete this event?");
	}
}

/*
 * Carousel Created by Alex Gonzalez
 *
 *  creates an animated carousel of a background image.
 */
function startCarousel(){
	var preload = new Array();
	var curIndex = 0;
	//preload images
	for (var i=0; i<carouselImages.length; i++){
		preload[i] = new Image();
		preload[i].src = images_basepath + carouselImages[i];
	}
	//randomize array
	carouselImages.sort(function (){return Math.round(Math.random())-0.5;});
	for (i=0; i<carouselImages.length; i++){ if (carouselImages[i] == getCookie("header_bg_image")) curIndex = i; }
	//create effect wrapper
	$("#headerWrap").css("background", "#000000 url("+images_basepath+carouselImages[curIndex]+") no-repeat top right")
	$("#headerWrap").append('<div id="headerTransition" style="display:none; background:#000000;"></div>');
	//start the carousel
	
	setTimeout(function (){ doCarousel(0); }, carouselinterval*1000);
}

function doCarousel(curIndex){
	setCookie("header_bg_image", carouselImages[curIndex], 1);
	$("#headerTransition").css("background", "#000000 url("+images_basepath+carouselImages[curIndex]+") no-repeat top right");
	$("#headerTransition").hide();
	$("#headerTransition").fadeIn(3000, function (){
		$(this).css("background", "none").hide();
		$("#headerWrap").css("background", "#000000 url("+images_basepath+carouselImages[curIndex]+") no-repeat top right");
		curIndex++;
		if (curIndex>=(carouselImages.length-1)) curIndex =0;
		setTimeout(function (){ doCarousel(curIndex); }, carouselinterval*1000);
	});
}

/*
 * Scrollable Areas by Alex Gonzalez
 *
 *  Creates horizontal scrollable div's
 */
function createScrollableAreasH(){
	$(".scrollable-h").each(function (){
		var _id = $(this).attr("id");
		if ($(this)[0].scrollWidth <= $(this).width()) return;
		scrollAreasH[_id] ={divScrollTo:0, dirscrollTo:0};
		$("#"+_id).children(":first")[0].scrollLeft = 0;
		$(this).css("overflow-x", "hidden").css("height", "100%");
		$(this).after('<div id="'+_id+'-scrollable-h-buttons" class="scrollable-h-buttons"> <a href="#" class="previous" title="Previous" onclick="return false;"><span>Previous</span></a><a href="#" class="next" title="Next" onclick="return false;"><span>Next</span></a></div>');
		
		$(this).mousewheel(function(objEvent, intDelta){
			var _id = $(this).attr("id");
			if (intDelta > 0){
				$("#"+_id+"-scrollable-h-buttons").find("a.previous").mousedown();
			
			}
			else if (intDelta < 0){
				$("#"+_id+"-scrollable-h-buttons").find("a.next").mousedown();
			}
			return false;
		});

		if ($(this)[0].scrollWidthH <= $(this).width()) $("#"+_id+"-scrollable-h-buttons").hide();
		$("#"+_id+"-scrollable-h-buttons").find("a.previous").addClass("disabled").mousedown(function (){
			if ($(this).css("opacity")!=1) return;
			var _id = $(this).parent().attr("id").replace("-scrollable-h-buttons", "");
			var offset = Math.round(($("#"+_id)[0].scrollLeft -1*scrollWidthH)/scrollWidthH)*scrollWidthH;
			var maxOffset = $("#"+_id)[0].scrollWidth- $("#"+_id).width();
			if (offset < maxOffset){ $("#"+_id+"-scrollable-h-buttons").find("a.next").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-h-buttons").find("a.next").addClass("disabled"); }
			if (offset > 0){ $("#"+_id+"-scrollable-h-buttons").find("a.previous").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-h-buttons").find("a.previous").addClass("disabled"); }
			autoScrollH(_id, offset);

		});
		$("#"+_id+"-scrollable-h-buttons").find("a.next").mousedown(function (){
			if ($(this).css("opacity")!=1) return;
			var _id = $(this).parent().attr("id").replace("-scrollable-h-buttons", "");
			var offset = Math.round(($("#"+_id)[0].scrollLeft + 1*scrollWidthH)/scrollWidthH)*scrollWidthH;
			var maxOffset = $("#"+_id)[0].scrollWidth- $("#"+_id).width();
			if (offset < maxOffset){ $("#"+_id+"-scrollable-h-buttons").find("a.next").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-h-buttons").find("a.next").addClass("disabled"); }
			if (offset > 0){ $("#"+_id+"-scrollable-h-buttons").find("a.previous").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-h-buttons").find("a.previous").addClass("disabled"); }
			
			autoScrollH(_id, offset);
		});
	});
	//animateScrollH();

}

function autoScrollH(container, offset){
	clearTimeout(scrollAutomationH);
	$("#"+container)[0].scrollLeft += (offset - $("#"+container)[0].scrollLeft)*0.1;
	scrollAutomationH= setTimeout(function (){autoScrollH(container, offset)}, 1);
}

/*
 * Scrollable Areas by Alex Gonzalez
 *
 *  Creates vertical scrollable div's
 */
function createScrollableAreasV(){
	$(".scrollable-v").each(function (){
		var _id = $(this).attr("id");
		if ($(this)[0].scrollHeight <= $(this).height()) return;
		scrollAreasV[_id] ={divScrollTo:0, dirscrollTo:0};
		$("#"+_id).children(":first")[0].scrollTop = 0;
		$(this).css("overflow-y", "hidden").css("width", "100%");
		$(this).after('<div id="'+_id+'-scrollable-v-buttons" class="scrollable-v-buttons"> <a href="#" class="previous" title="Previous" onclick="return false;"><span>Previous</span></a><a href="#" class="next" title="Next" onclick="return false;"><span>Next</span></a></div>');
		if ($(this)[0].scrollHeightV <= $(this).height()) $("#"+_id+"-scrollable-v-buttons").hide();
				
		$(this).mousewheel(function(objEvent, intDelta){
			var _id = $(this).attr("id");
			if (intDelta > 0){
				$("#"+_id+"-scrollable-v-buttons").find("a.previous").mousedown();
			
			}
			else if (intDelta < 0){
				$("#"+_id+"-scrollable-v-buttons").find("a.next").mousedown();
			}
			return false;
		});
	
		
		$("#"+_id+"-scrollable-v-buttons").find("a.previous").addClass("disabled").mousedown(function (){
			if ($(this).css("opacity")!=1) return;
			var _id = $(this).parent().attr("id").replace("-scrollable-v-buttons", "");
			var offset = Math.round(($("#"+_id)[0].scrollTop -1*scrollHeightV)/scrollHeightV)*scrollHeightV;
			var maxOffset = $("#"+_id)[0].scrollHeight- $("#"+_id).height();
			if (offset < maxOffset){ $("#"+_id+"-scrollable-v-buttons").find("a.next").removeClass("disabled");;
			}else{ $("#"+_id+"-scrollable-v-buttons").find("a.next").addClass("disabled"); }
			if (offset > 0){ $("#"+_id+"-scrollable-v-buttons").find("a.previous").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-v-buttons").find("a.previous").addClass("disabled"); }
			autoScrollV(_id, offset);

		});
		$("#"+_id+"-scrollable-v-buttons").find("a.next").mousedown(function (){
			if ($(this).css("opacity")!=1) return;
			var _id = $(this).parent().attr("id").replace("-scrollable-v-buttons", "");
			var offset = Math.round(($("#"+_id)[0].scrollTop + 1*scrollHeightV)/scrollHeightV)*scrollHeightV;
			var maxOffset = $("#"+_id)[0].scrollHeight- $("#"+_id).height();
			if (offset < maxOffset){ $("#"+_id+"-scrollable-v-buttons").find("a.next").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-v-buttons").find("a.next").addClass("disabled"); }
			if (offset > 0){ $("#"+_id+"-scrollable-v-buttons").find("a.previous").removeClass("disabled");
			}else{ $("#"+_id+"-scrollable-v-buttons").find("a.previous").addClass("disabled"); }
			
			autoScrollV(_id, offset);
		});
	});
	//animateScrollV();

}

function autoScrollV(container, offset){
	clearTimeout(scrollAutomationV);
	$("#"+container)[0].scrollTop += (offset - $("#"+container)[0].scrollTop)*0.1;
	scrollAutomationV= setTimeout(function (){autoScrollV(container, offset)}, 1);
}



/*
 *Accordion Menu by Alex Gonzalez
 *
 * This creates a one level accordion menu. 
 * NOTE: this script won't work with 3 or more nested UL tags.
 */
function createAccorionMenu(target){
	if ($(target).length==0) return;
	$(target).find("li:has(ul)").each(function (){ 
		this._maxheight = $(this).children("ul").height()
		$(this).children("ul").show().css({height:'0px', opacity:'0', overflow:'hidden'});
		if ($(this).find("li.selected").length>0) $(this).addClass("visible").children("ul").css({height:this._maxheight, opacity:'1'});
	});
	
	accordionMenu.selected = $(target).find("li:has(ul:has(li.selected))")[0];
	accordionMenu.target = target;
	accordionMenu.openSubMenu = function (subItem){
		clearTimeout(accordionMenu.reset_timeout);
		if (!$(subItem).hasClass("visible") ){
			$(this.target).find("li.visible").removeClass("visible").children("ul").stop().animate({height:'0px', opacity:'0'},"normal");
			$(subItem).addClass("visible").children("ul").stop().animate({height:subItem._maxheight+'px', opacity:'1'}, "normal");
		}
	};
	accordionMenu.resetSubMenu = function (){
		clearTimeout(accordionMenu.reset_timeout);
		accordionMenu.reset_timeout = setTimeout(function (){
			accordionMenu.openSubMenu(accordionMenu.selected);
		}, 1000);
	};
	
	$(target).find("li:has(ul)").mouseenter(function (){
		accordionMenu.openSubMenu(this);
	})
	$(target).mouseleave(function(){
		accordionMenu.resetSubMenu();
	});
}

/*
 * bigBox by Alex Gonzalez (ThickBox alternative)
 *
 *  Creates horizontal scrollable div's
 */
function makeThickBoxLinks(){
	if ($("a.bigBox").length>0){
		$("body").append('<div id="bigBox_container" style="z-index:150;display:none; opacity:0; position:absolute; left:50%; top:50%; background:#FFF; padding:10px; border:1px solid #000;"><img /></div>');
		hideBigBox = function (){ 
			clearTimeout($("#bigBox_container")[0].rollout_timeout);
			$("#bigBox_container")[0].rollout_timeout = setTimeout(function (){
				$("#bigBox_container").stop().animate({opacity:0},"normal", function (){$(this).hide();});
			},200);
		};
		
		$("#bigBox_container").mouseleave(hideBigBox).mouseenter(function (){ clearTimeout($("#bigBox_container")[0].rollout_timeout);$(this).stop().show().animate({opacity:1}, "normal");});
		$("a.bigBox").each(function (){
			var tempImage = new Image();
			tempImage.src = $(this).attr("href");
			this.preload = tempImage;
			$(this).mouseenter(function (){
				clearTimeout($("#bigBox_container")[0].rollout_timeout);
				$("#bigBox_container img").attr('src', this.preload.src).width(this.preload.width).height(this.preload.height);
				$("#bigBox_container").width(this.preload.width).height(this.preload.height).css('margin', (-this.preload.height/2)+'px 0 0 '+(-this.preload.width/2)+'px' ).stop().show().animate({opacity:1}, "normal");
			}).mouseleave(hideBigBox).click(function (){return false;});
		})
	}
}

/*
 * makeRotatingBanners by Alex Gonzalez
 *
 *  Creates a banner rotation from a stack.
 */
function makeRotatingBanners(target){
	if (typeof(bannerStack)!='undefined'){
		if (bannerStack.banners.length>1){
			bannerStack.target = target;
			for(banner in bannerStack.banners){
				bannerStack.banners[banner].preload = new Image();
				bannerStack.banners[banner].preload.src = bannerStack.banners[banner].image;
				
				$(target).find("ul li a:eq("+banner+")")[0].id = banner;
				$(target).find("ul li a:eq("+banner+")").click(function (){
					clearTimeout(bannerStack.rotateTimeout);
					bannerStack.bannerSelected = this.id;
					$(bannerStack.target).css("background",  "url("+$(target).find("img").attr("src")+") no-repeat 0px 0px");
					$(bannerStack.target).children("a").attr("href", (bannerStack.banners[this.id].link==''?'#':bannerStack.banners[this.id].link)).attr("target", ((bannerStack.banners[this.id].link.search(/^http/i)>=0)?'_blank':'_self'));
					$(bannerStack.target).find("img").css('opacity', '0').attr("alt",  bannerStack.banners[this.id].alt).attr("src",  bannerStack.bannerPath+bannerStack.banners[this.id].image).stop().animate({opacity:1}, "slow");
					$(this).parent("li").addClass("selected").siblings().removeClass("selected");
					return false;
				});
			}
			autoRotate();
		}else{
			$(target).find("ul").hide();
		}
	}
}
function autoRotate(){
	clearTimeout(bannerStack.rotateTimeout);
	var nextBanner = parseInt(bannerStack.bannerSelected)+1;
	if (nextBanner >= bannerStack.banners.length) nextBanner = 0;
	$(bannerStack.target).find("ul li a:eq("+nextBanner+")").click();
	bannerStack.rotateTimeout = setTimeout(autoRotate, 5000);
}

/*
 *Cookie functions by W3Schools [www.w3schools.com/JS/js_cookies.asp]
 *
 */
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 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 "";
}
