// This function acts like onload, except it doesn't wait for images to load.
// Add onload events here
function domReady() {
// Uncomment next line if you plan on using the footnote links script.
// Also be sure to place a call to that js file in the html
//	footnoteLinks('container','container');
	externalLinks();
	
	initShadowbox();

	// Common tabs initializer
  $('.ui-tabs').tabs();
}


function initShadowbox() {

	$('.locationChange a').click(
			function() {
				//alert("clicked");
				
				
				Shadowbox.open({
					content:	$("#changeLocationContent").html(),
					player:     "html",
					width: 		550,
					height: 	600,
					options: 	{
									displayNav:	true,
									viewportPadding: 2,
									onOpen:     function(element) {
													$('body').addClass('changeLocationModal');
													$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
													$('#sb-counter').css({display:'none'});
													$('#sb-title').css({clear:'both'});
													$('#sb-upper-right-close').remove();
													$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
												},
									onClose: 	function(element) {
													$('body').removeClass('changeLocationModal');
												}
								}
				});
				
				return false;
			}
		);
		
		
		$('.seeDetails a').click(
			function() {
				
				Shadowbox.open({
					content:	$(this).closest('.col, .container').find('.hiddenProductDetails').html(),
					player:     "html",
					width: 		550,
					height: 	800,
					options: 	{
									displayNav:	true,
									viewportPadding: 2,
									onOpen:     function(element) {
													$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
													$('#sb-counter').css({display:'none'});
													$('#sb-title').css({clear:'both'});
													$('#sb-upper-right-close').remove();
													$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
												}
								}
				});
				
				return false;
			}
		);
		
		$('a.emailEst').click(
			function() {
				
				Shadowbox.open({
					content:	"/estimator-email.aspx",
					player:     "iframe",
					width: 		590,
					height: 	800,
					options: 	{
									displayNav:	true,
									viewportPadding: 2,
									onOpen:     function(element) {
													$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
													$('#sb-counter').css({display:'none'});
													$('#sb-title').css({clear:'both'});
													$('#sb-upper-right-close').remove();
													$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
												}
								}
				});
				
				return false;
			}
		);
		
		$('input.removeBtn, .removeLink a').click(
			function() {
				
				Shadowbox.open({
					content:	$('#removeModal').html(),
					player:     "html",
					width: 		200,
					height: 	200,
					options: 	{
									displayNav:	true,
									viewportPadding: 2,
									onOpen:     function(element) {
													$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
													$('#sb-counter').css({display:'none'});
													$('#sb-title').css({clear:'both'});
													$('#sb-upper-right-close').remove();
													$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
												}
								}
				});
				
				return false;
			}
		);

}

function initLocationSearchPage() {
	initLocationSearchForm();
}

function initCantinaRegistrationPage() {
	initCantinaRegistrationForm();
}



function initLocationSearchForm() {
	$('#formZip').submit(
		
		function() {
			if(! /^\d{5}(-\d{4})?$/.test($("#zipCode")[0].value))
			{
				alert("Please enter a 5 digit zip code");
				return false;
			}
		}
	);
	
	var origZipText = $("#zipCode")[0].value;
	$("#zipCode").focus(
		function() {
			if($(this)[0].value == origZipText) {
				$(this)[0].value = '';
			}
			else {
				$(this).select();
			}
		}
	);
	
	$('#formCity').submit(
		
		function() {
			if(/^\s*$/.test($("#city")[0].value))
			{
				alert("Please enter a city");
				return false;
			}
			else if($("#state")[0].value == "") {
				alert("Please select a state");
				return false;
			}
		}
	);
	
	var origCityText = $("#city")[0].value;
	$("#city").focus(
		function() {
			if($(this)[0].value == origCityText) {
				$(this)[0].value = '';
			}
			else {
				$(this).select();
			}
		}
	);	
	
}

function initCantinaRegistrationForm() {
	var formRegistrationRules = getFormValidationRules(); // see the global form validation rules -> getFormValidationRules()
    //add custom form validation rules
    formRegistrationRules.rules = {

        confirmEmail: {
			equalTo: "#email"
        },
		password: {
            rangelength: [6,15],
            required: true
        },
        confirmPassword: {
			equalTo: "#password"
        },
		contactPhone: {
			phone: true
		},
		zipCode: {
			zipcode: true
		}
    };
	
	formRegistrationRules.messages = {
        password: {
            rangelength: "Your password must be between 6 and 15 characters."
        },
		month: {
			required: "Please enter your birth month."
		},
		day: {
			required: "Please enter your birth day."
		},
		zipCode: {
			zipcode: "Please enter a valid ZIP code."
		}
    };
	
	$('#formRegistration').validate(formRegistrationRules);
	//$('#formRegistration').validate();
}

jQuery.validator.addMethod("phone", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");


jQuery.validator.addMethod("zipcode", function(value, element) {
	return this.optional(element) || /^\d{5}(-\d{4})?$/.test(value);
}, "Please enter a valid zip code");

/********************************
* GLOBAL FORM VALIDATION SETTINGS
********************************/
/**
 * These are the basic rules for form validation
 * @see http://docs.jquery.com/Plugins/Validation
 * Note that form rules can be passed from the input class attribute (ex. class="required number")
 * Rules can also be customized via javascript within the form validation rules object
 */
function getFormValidationRules(){
    var formValidationRules = {
		debug: true,
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        focusInvalid: false,
        /*submitHandler: function() { alert("Submitted!") }, // if you need a custom submit handler */
        showErrors: function(errorMap, errorList){
            //alert($.dump(errorMap));
            //alert($.dump(errorList[0].element));
            $('#messageBox').html('');
            var msg = "";
            if(errorList.length > 0){
                $(errorList).each(function(){
                    msg += this.message + "<br />";
                });
                var title = "Error";
                // multiply the height by the number of errors
                var height = 21*(errorList.length);
                displayMessageBox(title, msg, height, errorList);
            }
        }

    }
    return formValidationRules;
}

$(function() {
    $('a[href$="estimator-home.aspx"]').click(function() {
        var link = this;
        // Trigger the location select modal if a location has not been selected
        if ( !getLocationCookie() ) {
            modalSetLocation = function(locationId) {
                setLocationCookie(locationId);
                window.location.href = link.href;
            };
            Shadowbox.open({
                content: $("#changeLocationContent").html(),
                player: "html",
                width: 550,
                height: 600,
                options: {
                    displayNav:	true,
                    viewportPadding: 2,
                    onOpen: function(element) {
                        $('body').addClass('changeLocationModal');
                        $('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
                        $('#sb-counter').css({display:'none'});
                        $('#sb-title').css({clear:'both'});
                        $('#sb-upper-right-close').remove();
                        $('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
                    },
                    onClose: function(element) {
                        $('body').removeClass('changeLocationModal');
                    }
                }
            });
            return false;
        }
    });
});


$(function() {
	$('.interactiveMenu').click(
		function(){
			
			if(!menu_home_tier) {
				modalSetLocation = function(locationId) {
					setLocationCookie(locationId);
					window.location.href = 'menu-home.aspx?interactive-menu=show';
				};
				Shadowbox.open({
					content: $("#changeLocationContent").html(),
					player: "html",
					width: 550,
					height: 600,
					options: {
						displayNav:	true,
						viewportPadding: 2,
						onOpen: function(element) {
							$('body').addClass('changeLocationModal');
							$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
							$('#sb-counter').css({display:'none'});
							$('#sb-title').css({clear:'both'});
							$('#sb-upper-right-close').remove();
							$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
						},
						onClose: function(element) {
							$('body').removeClass('changeLocationModal');
						}
					}
				});
				return false;
			}
			else {
				openInteractiveMenu(menu_home_tier);
			}
			
			return false;
		}
	);
});

function openInteractiveMenu(tierId) {
	var xml_path = '/docs/XML/menu'+tierId+'.xml';
			
	//alert('xml_path = ' + xml_path);

	Shadowbox.open({
		content:    '/docs/7495_menu_cs3.swf?whatMenu=' + xml_path,
		player:     "swf",
		width: 		1800,
		height: 	1253,
		options: 	{
						displayNav:	false,
						showMovieControls: false,
						viewportPadding: 0,
						onOpen:     function(element) {
										$('#sb-info').css('display', 'none');
										$('#sb-upper-right-close').css('display', 'none');
									},
						onClose:	function(element) {
										$('#sb-info').css('display', 'block');
										$('#sb-upper-right-close').css('display', 'block');
										window.location.href = 'menu-home.aspx';
									}
					}
	});
}

// Don't let user go to menu pages (other than menu-home) if no cookie set
$(function() {
    $('a[href*="menu-category.aspx"], a[href$="printable-menu.aspx"]').click(function() {
        var link = this;
        // Trigger the location select modal if a location has not been selected
        if ( !getLocationCookie() ) {
            modalSetLocation = function(locationId) {
                setLocationCookie(locationId);
                window.location.href = link.href;
            };
            Shadowbox.open({
                content: $("#changeLocationContent").html(),
                player: "html",
                width: 550,
                height: 600,
                options: {
                    displayNav:	true,
                    viewportPadding: 2,
                    onOpen: function(element) {
                        $('body').addClass('changeLocationModal');
                        $('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
                        $('#sb-counter').css({display:'none'});
                        $('#sb-title').css({clear:'both'});
                        $('#sb-upper-right-close').remove();
                        $('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
                    },
                    onClose: function(element) {
                        $('body').removeClass('changeLocationModal');
                    }
                }
            });
            return false;
        }
    });
});


/**
 * Automatic modal centering
 */
$(document).ready(function() {
    var f = function() {
        var $e = $('#messageBox').add('#emailOrderConfirmation');
        $e.each(function() {
            if ( $(this).dialog('isOpen') ) {
                $(this).dialog('option', 'position', 'center');
            }
        });
    };
    $(window).resize(f);
    $(window).scroll(f);
});


/********************************
* DHTML MESSAGE BOX
********************************/
function displayMessageBox(title, msg, height, errorList){
    //set minimum height to 100
    height += 37;
    height = height > 100 ? height : 100;
    $('#messageBox').html(msg);
    $('#messageBox').dialog({
        'title': title,
        width: 410,
        height: height,
        bgiframe: true,
        draggable: false,
        modal: true,
        resizable: false
    });
    //Focus the first error element after the dialog box is closed
    var firstErrorElement = errorList[0].element;
    $('#messageBox').bind('dialogclose', function(event, ui) {
        //alert(myVar);
        firstErrorElement.focus();
        $('#messageBox').dialog('destroy');
    });
}



function setLocationCookie(locationId) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+30);
	document.cookie = 'RestaurantId='+escape(locationId)+'; expires='+exdate.toGMTString() +'; path=/';
	//alert('set cookie to '+locationId);
}

function getLocationCookie() {
    var match = document.cookie.match(/RestaurantId=(.*?)(;|$)/);
    return match && match[1] ? match[1] : null;
}

function modalSetLocation(locationId, redirectUrl) {
	setLocationCookie(locationId); 
	//alert('test'); 
	//Shadowbox.close();
	//alert('redirecting to ' +redirectUrl);
	location.href = redirectUrl;  
	//Shadowbox.close();
}


function registerEmailEstimatorScripts() {
    $('input[name*=contact],select[name$=contactState]').change(function() { emailEstimatorUpdateDeliveryInfo(); }).keyup(function() { emailEstimatorUpdateDeliveryInfo(); });
    $('input[name$=sameAsAbove]').change(function() { emailEstimatorUpdateDeliveryInfo(); }).click(function() { emailEstimatorUpdateDeliveryInfo(); });
}

function emailEstimatorUpdateDeliveryInfo() {
	if($('input[name$=sameAsAbove]')[0].checked == true)
	{
	    $('input[name$=deliveryName]').val($('input[name$=contactName]').val());
	    /*Start Change by CTS on 2010-5-17: Add LastName & Change email template correction*/
	    $('input[name$=deliveryLastName]').val($('input[name$=contactLastName]').val());
	    /*End Change by CTS on 2010-5-17: Add LastName & Change email template correction*/
		$('input[name$=deliveryCompany]').val($('input[name$=contactCompany]').val());
		$('input[name$=deliveryPhone]').val($('input[name$=contactPhone]').val());
		$('input[name$=deliveryFax]').val($('input[name$=contactFax]').val());
		$('input[name$=deliveryEmail]').val($('input[name$=contactEmail]').val());
		$('input[name$=deliveryAddress1]').val($('input[name$=contactAddress1]').val());
		$('input[name$=deliveryAddress2]').val($('input[name$=contactAddress2]').val());
		$('input[name$=deliveryCity]').val($('input[name$=contactCity]').val());
		$('select[name$=deliveryState]').val($('select[name$=contactState]').val());
		$('input[name$=deliveryZip]').val($('input[name$=contactZip]').val());

		for (var v in Page_Validators) {
		    ValidatorValidate(Page_Validators[v]);
		}
	}
}

function shadowboxAlert(message) {
	$('#alertModal .messageText').html(message);
				
	Shadowbox.open({
		content:	$('#alertModal').html(),
		player:     "html",
		width: 		200,
		height: 	200,
		options: 	{
						displayNav:	true,
						viewportPadding: 2,
						onOpen:     function(element) {
										$('#sb-nav-close').html('Close [X]').css({width:'auto', float:'left'}).parent().css({float: 'left'});
										$('#sb-counter').css({display:'none'});
										$('#sb-title').css({clear:'both'});
										$('#sb-upper-right-close').remove();
										$('#sb-wrapper').prepend('<div id="sb-upper-right-close" style="float: right;"><a href="#" style="font-family: \'Lucida Grande\',Tahoma,sans-serif; font-size: 12px; text-decoration: none;  color: #ffffff;" onclick="Shadowbox.close();">Close [X]</a></div>');
									}
					}
	});
	
	return false;
}

function LocationSearchUCErrorHandler() {
	if(jQuery("input[id$='hdnShadowboxAlertMsg']").val()) {
		shadowboxAlert(jQuery("input[id$='hdnShadowboxAlertMsg']").val());
	}
}


$(function() {

	$("input[id$='finder_tbZip']").keypress(
		function(event) {
			// only allow digits and backspace/delete/arrows/tab
			// firefox puts characters in charCode, IE puts it in keycode
			if((event.charCode >= 48 && event.charCode <= 57)|| (event.keyCode >= 48 && event.keyCode <= 57) || ($.inArray(event.keyCode,[8,9,13,37,39,46]) != -1)  ) {
				// don't allow more than 5 characters, but allow backspaces or deletes
				if(this.value.length >= 5 && event.charCode != 0) {
					return false; 
				}
				else {
					return true;
				}
			}
			else {
				return false;
			}
		});
});
