jQuery ().ready (function () {
	observe_forms ();
	observe_clickable_elements ();
	observe_hover_elements ();

	observe_links ();
	observe_tell_a_friend_link ();
	observe_tell_a_friend_link_2 ();
	observe_view_map_link ();
	observe_view_product_video_link();
	observe_order_histories ();
	observe_items_per_page_selects ();

	return true;
});

observe_forms = function () {

	// observe buttons/links in a form that should submit that form
	// it sets the value of an input with the name "action" to the id of the element pressed

	// find the submit buttons and observe their clicks
	jQuery ('form :submit').click (function (event) {
		jQuery (this).parents ('form').map (function (submittedBy) {
			return function () {
				// set the input field "submittedBy"'s value to the id of the button pressed
				var updatedElements = jQuery (this).find (':input[name=submittedBy]').map (function () { jQuery (this).val (submittedBy); return this; } );
				// if no "submittedBy" input was found,  create a hidden one
				if (updatedElements.length <= 0)
					jQuery (this).prepend ('<input type="hidden" name="submittedBy" value="' + submittedBy + '" />');
			}
		} (this.id));
    });

	// observe the form submissions so that they can be handled via ajax instead of submitting normally
	jQuery ('form.jsAjaxForm').map (function () { jQuery (this).submit (function (event) {
		event.preventDefault ();

		// if there's no submitted by value,  find the first submit input and use that one's id as the "submittedBy" input
		var form = this;
		var validSubmittedByElements = jQuery (form).find (':input[name=submittedBy]').map (function () {if (jQuery (this).val () != '') return this; return null; } );

		if (!validSubmittedByElements.length) {
			jQuery (this).find (':submit:first').map (function () {
				var submittedBy = this.id;
				// set the input field "submittedBy"'s value to the id of the button pressed
				var updatedElements = jQuery (form).find (':input[name=submittedBy]').map (function () { jQuery (this).val (submittedBy); return this; } );
				// if no "submittedBy" input was found,  create a hidden one
				if (updatedElements.length <= 0)
					jQuery (form).prepend ('<input type="hidden" name="submittedBy" value="' + submittedBy + '" />');
				return this;
			});
		}


		// generate the parameters for the ajax request
		var requestParameters = new Object ();
		var fields = jQuery (this).find (":input").serializeArray ();
		jQuery.each (fields, function (i, field) {
			// need to account for arrays (ie. multiple selects and checkboxes)
			eval ("requestParameters." + jQuery (field).attr ('name') + " = jQuery (field).val ();");
		});
//		alert (var_dump (requestParameters));

		// submit the ajax request
		ajaxManager.request (jQuery (this).attr ('action'), { 'method': 'post', parameters: requestParameters });

		// reset any submittedBy fields
		var updatedElements = jQuery (this).find (':input[name=submittedBy]').map (function () { jQuery (this).val (''); return this; } );
    });	});

	return true;
}

// observe clickable things on the page and navigate to wherever their first anchor tag links to when clicked
observe_clickable_elements = function () {
/**
	// prototype version
	var pageElements = $$(".jsClickable");
	for (var count = 0; count < pageElements.length; count++) {
		pageElements[count].observe ("click", function (event) {
			event.stop;
			var linkElements = this.find_child_elements ("a");
			if (linkElements.length > 0)
				window.location = linkElements[0].readAttribute ("href");
		});
	}
/**/
	// jQuery version
	jQuery ('.jsClickable').click (function () {
		var destination = jQuery (this).find ('a').attr ('href');
		if (destination != '')
			window.location = destination;
    });
	return true;
}

// observe elements on the page that should get a hover class upon mouseover
observe_hover_elements = function () {
	// jQuery version
	jQuery ('.jsHover').mouseover (function () {
		jQuery (this).addClass ('hoverOn');
		jQuery (this).removeClass ('hoverOff');
    });
	jQuery ('.jsHover').mouseout (function () {
		jQuery (this).removeClass ('hoverOn');
		jQuery (this).addClass ('hoverOff');
    });
	jQuery ('.jsHover').addClass ('hoverOff');
	return true;
}

observe_links = function () {

	// login link
	jQuery ('.jsLogin').click (function () {
		var popover = environmentManager.create_popover ("login");
		popover.attach_to_element ($(this), { xSourcePoint: "right", xDestPoint: "right", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 80, yPixelOffset: -35 });
		popover.get_content_block_object ()
			.set_content_source_url ("/accounts/ajax_login.php");
//			.set_content_html ("hello there");
		popover.get_shell_object ()
			.set_title ("Log in to Baby Village")
			.set_width ("428px");
		popover.show ();
	});

	jQuery ('.jsLogin').removeClass ('jsLogin');

	// login link
	jQuery ('.jsForgottenPassword').click (function () {
		var popover = environmentManager.create_popover ("login");
		popover.attach_to_element ($(this), { xSourcePoint: "right", xDestPoint: "right", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 80, yPixelOffset: -35 });
		popover.get_content_block_object ()
			.set_content_source_url ("/accounts/ajax_forgotten_password.php?forgottenPasswordOnly=1");
//			.set_content_html ("hello there");
		popover.get_shell_object ()
			.set_title ("Forgotten password")
			.set_width ("428px");
		popover.show ();
	});

	jQuery ('.jsForgottenPassword').removeClass ('jsForgottenPassword');

}














align_elements = function (elementNamesArray, forceAlign, message) {
	var previousYOffset = 0;
	var maxHeight = 0;
	var inspectedElements = new Array ();
	var wereVisible = new Array ();

	// find out which ones were originally shown and show them anyway
	for (var count = 0; count < elementNamesArray.length; count++) {
		var liElementName = elementNamesArray[count];
		if ($(liElementName)) {
			wereVisible[count] = $(liElementName).visible ();
			$(liElementName).show ();
			$(liElementName).setStyle ({'height': 'auto'});
		}
	}

	for (var count = 0; count < elementNamesArray.length; count++) {
		var liElementName = elementNamesArray[count];

		if ($(liElementName)) {

			// see if this item has a different y offset to the previous items
			var temp = Position.cumulativeOffset ($(liElementName));

			var yOffset = parseInt (temp[1]);
//alert (yOffset);
			if ((yOffset != previousYOffset) && (inspectedElements.length > 0) && (!forceAlign)) {

				// adjust the height of each of the items in the row
				if ((inspectedElements.length > 1)) {
//alert (var_dump (inspectedElements));
					for (var count2 = 0; count2 < inspectedElements.length; count2++)
						$(inspectedElements[count2]).setStyle ( { "height" : maxHeight + "px" } );
				}

				// start the list of inspected elements off again
				var previousYOffset = 0;
				var maxHeight = 0;
				var inspectedElements = new Array ();

				// the row above this element has changed,  re-calculate it's offset
				var temp = Position.cumulativeOffset ($(liElementName));
				var yOffset = parseInt (temp[1]);
//				alert ('re calc: ' + yOffset);
			}

			// record the height of the current item
			var temp = $(liElementName).getDimensions ();
			var height = parseInt (temp.height);
			if (height > maxHeight)
				maxHeight = height;
			inspectedElements[inspectedElements.length] = liElementName;

//if (liElementName == 'descriptionBlockDiningGeneric')
//				alert (yOffset + " " + message + " " + height);

			previousYOffset = yOffset;
		}
	}

	// if there are any elements that were left over
	if (inspectedElements.length > 0) {
//alert ('rah');
//alert (var_dump (inspectedElements));
		// adjust the height of each of the items in the row
		for (var count2 = 0; count2 < inspectedElements.length; count2++)
			$(inspectedElements[count2]).setStyle ( { "height" : maxHeight + "px" } );
	}

	// return each element back to it's original show/hide status
	for (var count = 0; count < elementNamesArray.length; count++) {
		var liElementName = elementNamesArray[count];
		if ($(liElementName)) {
			if (!wereVisible[count])
				$(liElementName).hide ();
		}
	}

	return true;
}

vertically_center_elements = function (elementNamesArray, usePadding) {
	return vertically_align_elements (elementNamesArray, usePadding, 'center');
}

vertically_bottom_elements = function (elementNamesArray, usePadding) {
	return vertically_align_elements (elementNamesArray, usePadding, 'bottom');
}

vertically_align_elements = function (elementNamesArray, usePadding, position) {

	for (var count = 0; count < elementNamesArray.length; count++) {
		var element = $(elementNamesArray[count]);
		if ($(element)) {

			var parentElement = element.ancestors ().first ();

			var heightElement = parseInt (element.getHeight ());
			var heightParentElement = parseInt (parentElement.getHeight ());
			if (position == 'bottom')
				var newHeight = Math.max (0, String (parseInt ((heightParentElement - heightElement))));	// make sure the offset isn't less than 0
			else
				var newHeight = Math.max (0, String (parseInt ((heightParentElement - heightElement) / 2)));	// make sure the offset isn't less than 0

//			alert (elementNamesArray[count] + " " + heightElement + " " + heightParentElement + " " + newHeight + " " + element.ancestors ().first ().outerHTML);

			if (usePadding)
				element.setStyle ( { "paddingTop": newHeight + "px" });
			else
				element.setStyle ( { "marginTop": newHeight + "px" });
		}

	}

	return true;
}



// observe the links on the page that cause a "tell a friend" popover to appear
observe_tell_a_friend_link = function () {
	jQuery ('.jsTellAFriend').click (function (e) {
		var popover = environmentManager.create_popover ("tellAFriend", "popoverTypeTellAFriend");
		popover.attach_to_element (this, { xSourcePoint: "middle", xDestPoint: "middle", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 0, yPixelOffset: -20 });
		popover.get_content_block_object ()
			.set_content_source_url ("/accounts/ajax_tell_a_friend.php");
//			.set_content_html ("hello there");
//			.set_content_source_dom_id ("template_listAllSales");
		popover.get_shell_object ()
//			.set_use_title_bar (false)
			.set_title ("Tell A Friend")
			.set_width ("515px");
		popover.show ();
	});
}

// observe the links on the page that cause a "tell a friend" popover to appear
observe_tell_a_friend_link_2 = function () {
	jQuery ('.jsTellAFriendContactList').click (function (e) {
		var popover = environmentManager.create_popover ("tellAFriendContactList", "popoverTypeTellAFriend");
		popover.attach_to_element (this, { xSourcePoint: "middle", xDestPoint: "middle", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 0, yPixelOffset: -20 });
		popover.get_content_block_object ()
			.set_content_source_url ("/accounts/ajax_tell_a_friend_contact_list.php");
//			.set_content_html ("hello there");
//			.set_content_source_dom_id ("template_listAllSales");
		popover.get_shell_object ()
//			.set_use_title_bar (false)
			.set_title ("Tell A Friend")
			.set_width ("550px");
		popover.show ();
	});
}


observe_add_review = function () {
	// watch for jsUpdateChallenge clicks
	jQuery ('.jsReview').click (function (e) {
		e.stopPropagation ();
		var popover = environmentManager.create_popover ("addReview", "popoverTypeProductReview");
		popover.position_on_screen ({ xSourcePoint: "middle", xDestPoint: "middle", ySourcePoint: "top", yDestPoint: "top", ySourcePercentOffset: 7 });
		popover.get_content_block_object ()
			.set_content_source_url ("/ajax_add_review.php", {productElementId: this.id});
		popover.get_shell_object ()
			.set_title ("Add review")
			.set_width ("615px");
		popover.show ();
	});
	
	return true;

}



// observe the links on the page that cause a "view map" popover to appear
observe_view_map_link = function () {
	jQuery ('.jsViewMap').click (function (e) {
		var popover = environmentManager.create_popover ("viewMap", "popoverType1");
		popover.attach_to_element (this, { xSourcePoint: "middle", xDestPoint: "middle", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 0, yPixelOffset: -20 });
		popover.get_content_block_object ()
			.set_content_source_url ("/ajax_view_map.php",{mapElementId: this.id});
//			.set_content_html ("hello there");
//			.set_content_source_dom_id ("template_listAllSales");
		popover.get_shell_object ()
//			.set_use_title_bar (false)
			.set_title ("Baby Village - Bondi Junction")
			.set_width ("700px");
		popover.show ();
	});
}

observe_view_product_video_link = function () {
	jQuery ('.jsViewVideo').click (function (e) {
		var popover = environmentManager.create_popover ("viewMap", "popoverType1");
		popover.attach_to_element (this, { xSourcePoint: "middle", xDestPoint: "middle", ySourcePoint: "top", yDestPoint: "top", xPixelOffset: 0, yPixelOffset: -20 });
		popover.get_content_block_object ()
			.set_content_source_url ("/ajax_view_video.php",{mapElementId: this.id});
//			.set_content_html ("hello there");
//			.set_content_source_dom_id ("template_listAllSales");
		popover.get_shell_object ()
//			.set_use_title_bar (false)
			.set_title ("Baby Village")
			.set_width ("560px");
		popover.show ();
	});
}

observe_order_histories = function () {

	// login link
	jQuery ('.jsOrderHistory').click (function () {
		var shoppingCartId = this.id.replace (/[^0-9]+/, '');
		jQuery ("#moreInfo" + shoppingCartId).map (function () {
			if (jQuery (this).is (':visible')) {
				jQuery (this).hide ("blind");
				jQuery ("#link_moreInfo" + shoppingCartId).html ("+");
				jQuery ("#link_moreInfoText" + shoppingCartId).html ("more info");
			}
			else {
				jQuery (this).show ("blind");
				jQuery ("#link_moreInfo" + shoppingCartId).html ("-");
				jQuery ("#link_moreInfoText" + shoppingCartId).html ("less info");
			}
		});
//		alert (temp.visible ());
	});

}


// let the use choose how many products to show per page (select inputs)
observe_items_per_page_selects = function () {

	// login link
	jQuery ('.jsItemsPerPage').change (function () {
		jQuery.cookie ('itemsPerPage', jQuery (this).val (), { path: '/' });
//		jQuery.cookie ('resetStart', 1, { path: '/' });

		// reload the page to show more/less results
//		location.reload ();
/**/
		// load the page to show more/less results
		// remove "start" from the query string so the user goes back to the first page of the results
		var queryString = window.location.search.substring (1);
		var queryStringParts = queryString.split ('&');
		var newQueryStringParts = new Array ();
		for (i = 0; i < queryStringParts.length; i++) {
			var temp = queryStringParts[i].split ('=');
			// don't include the "start" value so the user goes back to the first page
			if (temp[0] != 'start')
				newQueryStringParts.push (queryStringParts[i]);
		}
		var newQueryString
		if (newQueryStringParts.length)
			var newQueryString = '?' + newQueryStringParts.join ('&');
		location.href = newQueryString;
/**/
	});
}





track_page_item_click = function (string) {
	if (pageTracker == undefined) {
		var pageTracker = _gat._getTracker("UA-11293500-1");
		pageTracker._initData();
	}
	pageTracker._trackPageview (string);
}

