YAHOO.util.Event.onDOMReady(function () {
	
	var winwidth = document.all ? document.body.clientWidth : window.innerWidth; 
	document.getElementById('bg-wrapper').style.padding = '0 ' + ((winwidth - 1000) / 2) + 'px';
}); 


/*
     Initialize and render the MenuBar when its elements are ready 
     to be scripted.
*/

YAHOO.util.Event.onContentReady("nav", function () {

	if (!document.getElementById("kula-forum"))	{
	    /*
	         Instantiate a MenuBar:  The first argument passed to the 
	         constructor is the id of the element in the page 
	         representing the MenuBar; the second is an object literal 
	         of configuration properties.
	    */
		
	    var oMenuBar = new YAHOO.widget.MenuBar("nav", { 
                autosubmenudisplay: true, 
                hidedelay: 750, 
                lazyload: true });
	
	    oMenuBar.render();
	}
});



YAHOO.namespace("sg_signin.container");

YAHOO.util.Event.onContentReady("sg_signin", function () {
	
	var checkToken = function(o)	{
		
		if (o.responseText == 'token error')	{
			alert('Error, please try again');
			window.location.reload();
			return false;
		}
		
		return true;
		
	}
	
	// Hide the Member ID field
	if (document.getElementById('wpsc_checkout_form_20'))	{
		document.getElementById('wpsc_checkout_form_20').parentNode.style.display = 'none';
	}
	
	var replaceHtml = function (el, html) {
		var oldEl = typeof el === "string" ? document.getElementById(el) : el;
		var newEl = oldEl.cloneNode(false);
		newEl.innerHTML = html;
		oldEl.parentNode.replaceChild(newEl, oldEl);
		/* Since we just removed the old element from the DOM, return a reference
		to the new element, which can be used to restore variable references. */
		return newEl;
	};
	
	var handleClearSignInSuccess = function(o)	{
		
		if (o.responseText !== undefined)	{
			
			if (!checkToken(o))	{
				return;
			}
			
			var response = o.responseText; 
			response = response.split("<!")[0];
			eval(response);
			
			// return the sg_signin_greeting to it's original state
			document.getElementById('sg_signin_greeting').innerHTML = sg_signin_greeting_string;
			
			// return the member info form to it's original state
			document.getElementById('customer_info').innerHTML = customer_info;
			
			// return the shopping cart summary to it's state
			replaceHtml('shopping_cart_summary', shopping_cart_summary);
			
			YAHOO.util.Event.addListener(["sg_signin_open","sg_signin_open_img"], "click", YAHOO.sg_signin.container.choose_pose.show, YAHOO.sg_signin.container.choose_pose, true);
			
			// Hide the Member ID field
			if (document.getElementById('wpsc_checkout_form_20'))	{
				document.getElementById('wpsc_checkout_form_20').parentNode.style.display = 'none';
			}
		}
	};

	var handleClearSignInFailure = function(o){
		alert("handleClearSignInFailure failed: " + o.status);
	};

	var clearSignInCallback =
		{
		  success:handleClearSignInSuccess,
		  failure:handleClearSignInFailure
		};
	
	var clearSignIn = function()	{
		var sUrl = location.href;
		var postData = "cart_action=sg_signin&step=clear_signin";
		var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, clearSignInCallback, postData);
	}
	
	// Define various event handlers for Dialog
	var handleSubmit = function() {
		this.submit();
	};
	var handleCancel = function() {
		this.cancel();
	};
	var handleSuccess = function(o) {
		
		if (!checkToken(o))	{
			return;
		}
		
		var response = o.responseText; 
		response = response.split("<!")[0];
		
       		 eval(response);
		
		YAHOO.sg_signin.BasicLocal = function() {
			// Use a LocalDataSource
			var oDS = new YAHOO.util.LocalDataSource(members);
			// Optional to define fields for single-dimensional array
			oDS.responseSchema = {fields : ["state"]};
	
			// Instantiate the AutoComplete
			var oAC = new YAHOO.widget.AutoComplete("signin_name", "signin_name_container", oDS);
	
			oAC.animVert = false;
			oAC.prehighlightClassName = "yui-ac-prehighlight";
			oAC.useShadow = true;
			
			return {
			    oDS: oDS,
			    oAC: oAC
			};
		}();
		
		YAHOO.sg_signin.container.choose_pose.hide();
		YAHOO.util.Dom.addClass('loading_pose', 'delay_show');
		YAHOO.sg_signin.container.enter_name.show();
	
	};
	var handleFailure = function(o) {
		alert("Submission failed: " + o.status);
	};
	
	var showChoosePose = function()	{
		YAHOO.util.Dom.removeClass('choose_pose', 'delay_show');
		YAHOO.sg_signin.container.choose_pose.show();
	};
	
	// Dialog 1: Choose Pose
	YAHOO.sg_signin.container.choose_pose = new YAHOO.widget.Dialog("choose_pose", 
		{ width : "600px",
		height: "530px",
		fixedcenter : true,
		visible : false, 
		constraintoviewport : true,
		buttons : [
		{ text:"Cancel", handler:handleCancel } ],
		hideaftersubmit : false,
		modal: true
		});

	// Validate the entries in the form to require that both first and last name are entered
	YAHOO.sg_signin.container.choose_pose.validate = function() {
		return true;
	};

	// Wire up the success and failure handlers
	YAHOO.sg_signin.container.choose_pose.callback = { 
		success: handleSuccess,
		failure: handleFailure };
	
	// Render the Dialog
	YAHOO.sg_signin.container.choose_pose.render();
	// end Dialog 1 
	
	YAHOO.util.Event.addListener(["sg_signin_open","sg_signin_open_img"], "click", showChoosePose, YAHOO.sg_signin.container.choose_pose, true);
	YAHOO.util.Event.addListener("clear_sign_in", "click", clearSignIn);
	
	// Dialog 2: Enter name
	
	// Define various event handlers for Dialog
	var handleSubmitEnterName = function() {
		YAHOO.util.Dom.removeClass('loading_name', 'delay_show');
		this.submit();
	};
	var handleCancelEnterName = function() {
		document.getElementByID('signin_name').value = '';
		this.cancel();
	};
	
	var handleSuccessEnterName = function(o) {
		
		if (!checkToken(o))	{
			return;
		}
		
		YAHOO.util.Dom.addClass('loading_name', 'delay_show');
		
		var response = o.responseText; 
		response = response.split("<!")[0];

		eval(response);

		if (error != '')	{
			YAHOO.util.Dom.addClass('enter_name_error', 'error');
			document.getElementById('enter_name_error').innerHTML = error;
		}
		
		else if (typeof(member) == 'object')	{
			
			// clear out the error if it existed before
			document.getElementById('enter_name_error').innerHTML = '';
			YAHOO.util.Dom.removeClass('enter_name_error', 'error');
			
			
			// Add the sign in greeting
			document.getElementById('sg_signin_greeting').innerHTML = sg_signin_greeting_string;
			
			// replace the customer info div
			document.getElementById('customer_info').innerHTML = customer_info;
			
			// refresh the shopping cart summary
			if (sg_coupon)	{
				replaceHtml('shopping_cart_summary', shopping_cart_summary);
			}
			
			YAHOO.util.Event.addListener("clear_sign_in", "click", clearSignIn);
			
			// hide the enter name dialog
			YAHOO.sg_signin.container.enter_name.hide();
			
		}
	};
	
	var handleFailureEnterName = function(o) {
		alert("Submission failed: " + o.status);
	};

	var returnToPoses = function()	{
		YAHOO.sg_signin.container.enter_name.hide();
		YAHOO.util.Dom.addClass('loading_pose', 'delay_show');
		YAHOO.sg_signin.container.choose_pose.show();
	};

	YAHOO.sg_signin.container.enter_name = new YAHOO.widget.Dialog("enter_name", 
		{ width : "35em",
		fixedcenter : true,
		visible : false, 
		constraintoviewport : true,
		buttons : [ { text:"Submit", handler:handleSubmitEnterName, isDefault:true },
		  { text:"Cancel", handler:handleCancel } ],
		hideaftersubmit : false,
		modal: true
		});

	// Validate the entries in the form to require that both first and last name are entered
	YAHOO.sg_signin.container.enter_name.validate = function() {
		return true;
	};

	// Wire up the success and failure handlers 
	YAHOO.sg_signin.container.enter_name.callback = { success: handleSuccessEnterName,
		failure: handleFailureEnterName };
	
	// Render the Dialog
	YAHOO.sg_signin.container.enter_name.render();

	YAHOO.util.Event.addListener("return_to_poses", "click", returnToPoses);
	
	var poseClick = function()	{
		document.getElementById('sg_pose').value = this.id;
		YAHOO.util.Dom.removeClass('loading_pose', 'delay_show');
		document.getElementById('sg_pose_submit').click();
	};
	
	var poses = ["Boat", "Bow", "Bridge", "Camel", "Cobra", "Dancer", "Half Moon", "Lotus", "Plow", "Tree", "Triangle", "Warrior II"];
				
	YAHOO.util.Event.addListener(poses, "click", poseClick);
	
	// end Dialog 2
	
});

function addLoadEvent(func) {
	var oldonload=window.onload;
	if(typeof window.onload!='function')	{
			window.onload=func;
	}	
	else{
		window.onload=function()	{
			oldonload();func();
		}
	}
}

giftCard = {
	
	el_deliveryEmail: null,
	el_deliveryMail: null,
	el_deliveryStore: null,

	deliveryOption: null,
	
	init: function() {
		giftCard.el_deliveryEmail = document.getElementById('delivery_by_email');
		giftCard.el_deliveryMail = document.getElementById('delivery_by_mail');
		giftCard.el_deliveryStore = document.getElementById('delivery_by_store');
		giftCard.initEvents();
		
	},
	
	initEvents:function()	{
		
		// add onchanges to each of the checkboxes
		if (giftCard.deliveryOption == null)	{
			giftCard.deliveryOption = document.getElementsByName('gc[delivery_option]');
		}
		
		var current_selection = 0;
		
		if (giftCard.deliveryOption == null)	{
			return;	
		}
		
		for (var i=0; i < giftCard.deliveryOption.length; i++)	{
			
			current_selection = giftCard.deliveryOption[i];
			
			if (current_selection.value == 'email' && current_selection.checked)	{
				giftCard.el_deliveryEmail.className = 'show';
			}
			else if (current_selection.value == 'mail' && current_selection.checked)	{
				giftCard.el_deliveryMail.className = 'show';
			}
			else if (current_selection.value == 'store' && current_selection.checked)	{
				giftCard.el_deliveryStore.className = 'show';
			}
			
			(function() {
				var oc = giftCard.deliveryOption[i];
				oc.onclick = function() {
					
					if (oc.value == 'email' && oc.checked)	{
						giftCard.el_deliveryEmail.className = 'show';
						giftCard.el_deliveryMail.className = 'hide';
						giftCard.el_deliveryStore.className = 'hide';
					}
					else if (oc.value == 'mail' && oc.checked)	{
						giftCard.el_deliveryEmail.className = 'hide';
						giftCard.el_deliveryMail.className = 'show';
						giftCard.el_deliveryStore.className = 'hide';
					}
					else if (oc.value == 'store' && current_selection.checked)	{
						giftCard.el_deliveryEmail.className = 'hide';
						giftCard.el_deliveryMail.className = 'hide';
						giftCard.el_deliveryStore.className = 'show';
					}
				}
			})();
		}
	},
	
	checkAll: function(el_collection, checkValue)	{
		
		for (var i=0; i < el_collection.length; i++)	{
			if (typeof(el_collection[i]) == 'object')	{
				if (el_collection[i].value == checkValue)	{
					el_collection[i].checked = 1;
				}
				else	{
					el_collection[i].checked = 0;
				}
			}
		}
	}
}
addLoadEvent(giftCard.init);


YAHOO.namespace("confirm_cart.container");

function initConfirmCartContainer() {
	
	YAHOO.confirm_cart.container.panel1 = new YAHOO.widget.Panel("confirm_add_to_cart", { 
			width:"320px", 
			visible:false, 
			constraintoviewport:true, 
			fixedcenter : true,
			visible : false 
	} );
	YAHOO.confirm_cart.container.panel1.render();
	
//	YAHOO.util.Dom.addClass('confirm_add_to_cart', 'delay_show');
}

YAHOO.util.Event.onContentReady("confirm_add_to_cart", function () {
	initConfirmCartContainer();
});

function confirmWindowClose()	{
	YAHOO.confirm_cart.container.panel1.hide();
}

/** 
Schedule JS
*/
YAHOO.namespace("schedule.container");

YAHOO.util.Event.onContentReady("schedule", function () {
	
	var reloadSchedule = function(e, el)	{
		
		YAHOO.util.Event.preventDefault(e); // prevent the click from occuring
		
		var start_offset = el.getAttribute('title');
		
		var sUrl = "?load_calendar_action=reload_schedule&start_offset="+start_offset;
		
		var callback = {
			
			success: function(o) {
				
				var response = o.responseText; 
				response = response.split("<!")[0];
				eval(response);
				
				if (schedule_string != '')	{
					document.getElementById('schedule_wrapper').innerHTML = schedule_string;	
					setScheduleReloads();
					setScheduleInfoPanels();
					var scheduleID = document.getElementById('schedule');
					YAHOO.util.Dom.setStyle(scheduleID, 'opacity', '0');
					var aniObj = new YAHOO.util.Anim(scheduleID, { opacity: {from: 0, to: 1 } }, '1', YAHOO.util.Easing.easeIn);
					aniObj.animate();
				}
				
				return false;
				
			},
			
			failure: function(o) {
				// alert("Something went wrong"); //FAILURE
			}
		} 
	
		var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
		
		return false;
	};
	
	var loadClassDescription = function(e, el)	{
		
		YAHOO.util.Event.preventDefault(e); // prevent the click from occuring
		
		var load_calendar_url = el.getAttribute('href');
		
		var sUrl = "?load_calendar_action=schedule_info_panel&load_calendar_url="+load_calendar_url+"/";
		
		var callback = {
			
			success: function(o) {
				
				var response = o.responseText; 
				response = response.split("<!")[0];
				eval(response);
				
				if (panel_title != '')	{
					YAHOO.schedule.container.info_panel.setHeader(panel_title);
					YAHOO.schedule.container.info_panel.setBody(class_type);
					YAHOO.schedule.container.info_panel.setFooter("<a style='cursor:pointer; cursor:hand;' id='close_schedule_panel'>Close this window</a>");
					YAHOO.schedule.container.info_panel.render("container");
					YAHOO.schedule.container.info_panel.show();
					YAHOO.util.Event.addListener(document.getElementById('close_schedule_panel'), "click", confirmScheduleClose);
					
					if (load_calendar_url.search('locations'))	{
						loadLocationMaps(load_calendar_url);
					}
							
				}
				
				return false;
				
			},
			
			failure: function(o) {
				// alert("Something went wrong"); //FAILURE
			}
		} 
	
		var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
		
		return false;
		
	};
	
	var confirmScheduleClose = function()	{
		YAHOO.schedule.container.info_panel.hide();
	};
	
	// Instantiate a Panel from script
	YAHOO.schedule.container.info_panel = new YAHOO.widget.Panel("info_panel", { width:"650px", visible:false, draggable:false, fixedcenter: true, close:true, zIndex: 100 } );
	
	var setScheduleInfoPanels = function()	{
	
		var class_types = YAHOO.util.Dom.getElementsByClassName('schedule_info_panel');
		
		for (var i=0; i < class_types.length; i++)	{
			
			YAHOO.util.Event.addListener(class_types[i], "click", loadClassDescription, class_types[i], true);
			//class_types[i].setAttribute('title', class_types[i].getAttribute('href'));
			//class_types[i].removeAttribute('href');
			
		}
	};
	
	setScheduleInfoPanels();
	
	var loadLocationMaps = function(url)	{
		if (url.search('austin') != -1) YAHOO.schedule.container.info_panel.showEvent.subscribe(showKulaMap('map_austin', 49.248889,-122.817814, "Austin Station"), YAHOO.schedule.container.info_panel, true);
		if (url.search('newport') != -1) YAHOO.schedule.container.info_panel.showEvent.subscribe(showKulaMap('map_newport', 49.282900,-122.826507, "Newport Village"), YAHOO.schedule.container.info_panel, true);
		if (url.search('meridian') != -1) YAHOO.schedule.container.info_panel.showEvent.subscribe(showKulaMap('map_meridian', 49.292216,-122.753779, "Meridian Crossing"), YAHOO.schedule.container.info_panel, true);
	};
	
	var setScheduleReloads = function()	{
		var schedule_reloads = YAHOO.util.Dom.getElementsByClassName('schedule_reload');
		for (var i=0; i < schedule_reloads.length; i++)	{
			YAHOO.util.Event.addListener(schedule_reloads[i], "click", reloadSchedule, schedule_reloads[i], true);
		}
	};
	
	setScheduleReloads();
	
});

YAHOO.namespace("schedule.maps");

//YAHOO.schedule.maps = Array;

function showKulaMap(el_id, latitude, longitude, map_title)	{
	
	if (document.getElementById(el_id))	{
		
		var myLatlng = new google.maps.LatLng(latitude, longitude);
		
		var myOptions = {
	      zoom: 14,
	      center: myLatlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
	      navigationControl: false,
		  mapTypeControl: false,
		  scaleControl: true
	    }
	    var this_map = new google.maps.Map(document.getElementById(el_id), myOptions);
		
		var marker = new google.maps.Marker({
	        position: myLatlng, 
	        map: this_map,
	        title: map_title,
	        icon: "http://labs.google.com/ridefinder/images/mm_20_red.png",
			shadow: "http://labs.google.com/ridefinder/images/mm_20_shadow.png"
	    });  
	}
}

YAHOO.namespace("schedule.calendar");

YAHOO.schedule.calendar.init = function() {

    function handleSelect(type,args,obj) {
        var dates = args[0]; 
        var date = dates[0];
        var year = date[0], month = date[1], day = date[2];
        
        var txtDate1 = document.getElementById("date1");
        txtDate1.value = month + "/" + day + "/" + year;
        
        document.getElementById('cal1Container').style.display = 'none';
		
    }

    function updateCal() {
    	
        var txtDate1 = document.getElementById("date1");

        if (txtDate1.value != "") {
            YAHOO.schedule.calendar.cal1.select(txtDate1.value);
            var selectedDates = YAHOO.schedule.calendar.cal1.getSelectedDates();
            if (selectedDates.length > 0) {
                var firstDate = selectedDates[0];
                YAHOO.schedule.calendar.cal1.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear());
                YAHOO.schedule.calendar.cal1.render();
            } else {
                alert("Cannot select a date before 1/1/2006 or after 12/31/2010");
            }
            
        }
    }

    // For this example page, stop the Form from being submitted, and update the cal instead
    function handleSubmit(e) {
        updateCal();
        YAHOO.util.Event.preventDefault(e);
    }
    
    YAHOO.schedule.calendar.cal1 = new YAHOO.widget.CalendarGroup("cal1","cal1Container", 
                                                                { pages:2});
    YAHOO.schedule.calendar.cal1.selectEvent.subscribe(handleSelect, YAHOO.schedule.calendar.cal1, true);
    YAHOO.schedule.calendar.cal1.render();

    YAHOO.util.Event.addListener("update", "click", updateCal);
    YAHOO.util.Event.addListener("dates", "submit", handleSubmit);
}

YAHOO.util.Event.onDOMReady(YAHOO.schedule.calendar.init);

YAHOO.util.Event.onContentReady("date1", function()	{
	
	var showCal = function()	{
		
		document.getElementById('cal1Container').style.display = 'inline';
		document.getElementById('cal1Container').style.visibility = 'visible';
		document.getElementById('cal1Container').style.position = 'absolute';
	}
	
	YAHOO.util.Event.addListener("date1", "click", showCal);
	
	
	 
});



