var SarahBaker = 
{
	Page: 
	{
		map: "",
		
		init: function()
		{
			if($(".accommodation-gallery").length)
			{
				$(".accommodation-gallery a").fancybox(
				{
					"titlePosition": "over",
					"transitionIn": "fade",
					"transitionOut": "fade",
					"centerOnScroll": true,
					"onComplete":function() 
					{
						$("#fancybox-wrap").hover(function() 
						{
							$("#fancybox-title").show();
						}, 
						function() 
						{
							$("#fancybox-title").hide();
						});
					}
				});
			}
			
			$.ajax(
			{
				type:"GET",
				url:"/photos.xml",
				dataType:"xml",
				success:function(xml)
				{
					$(xml).find("photo").each(function()
					{
						$.preLoadImages("/media/" + $(this).find("folder").text() + "/" + $(this).find("filename").text());
					});
				}
			});
			
			

			$.preLoadImages(
				"/media/logo.png",			
				"/media/header-background.png",
				"/media/cooking-for-fun.jpg",
				"/media/cooking-for-life.jpg",
				"/media/cooking-for-you.jpg",
				"/media/body-background.png",
				"/media/slow-food-ireland.png",
				"/media/twitter.png",
				"/media/whats-on-sidebar.jpg",
				"/media/whats-on-sidebar-1.jpg",
				"/media/whats-on-sidebar-2.jpg",
				"/media/whats-on-sidebar-3.jpg",
				"/media/whats-on-sidebar-4.jpg",
				"/media/whats-on-sidebar-5.jpg",
				"/media/why-sarah-baker-0.jpg",
				"/media/why-sarah-baker-1.jpg",
				"/media/why-sarah-baker-2.jpg",
				"/media/why-sarah-baker-3.jpg",
				"/media/why-sarah-baker-4.jpg",
				"/media/why-sarah-baker-5.jpg",
				"/media/level0.png",
				"/media/level1.png",
				"/media/level2.png",
				"/media/level3.png",
				"/media/level4.png",
				"/media/level5.png",
				"/media/cart.png",
				"/media/cc.png"
			);
			
			if($("#twitter").length)
			{
				$("#twitter").getTwitter(
				{
					userName:"sarahbakercooks",
					numTweets:5,
					loaderText:"Loading tweets...",
					slideIn:true,
					slideDuration:750,
					showHeading:false,
					headingText:"Latest Tweets",
					showProfileLink:false,
					showTimestamp:true
				});
			}	
				
			//SarahBaker.Page.setAnchor();
				
			$("a").filter(function()
			{
				return this.hostname && this.hostname !== location.hostname;
			})
			.after(" <img src=\"/media/external.png\" alt=\"This is an external link\" title=\"This is an external link\">")
			.click(function()
			{
				window.open(this.href);
			
				return false;
			});
					
			if($(".autofade").length)
			{
				setTimeout(function()
				{
					$(".autofade").fadeOut().slideUp("slow"); 
				}, 4000);	
			}
			
			if($("#map").length)
			{
				SarahBaker.Page.showGoogleMap();
			}
			
			if($("frmContactForm").length)
			{
				if(!Modernizr.input.placeholder)
				{
					$("input[type=text]").focus(function()
					{ 
	    				if($(this).val() == $(this).attr("defaultValue"))
	    				{
	      					$(this).val("");
	    				}
	  				});
	  
	  				$("input[type=text]").blur(function()
	  				{
	    				if($(this).val() == "")
	    				{
	    		 	 		$(this).val($(this).attr("defaultValue"));
	    				} 
	  				});
				}
			}			
		},
		
		setAnchor: function()
		{
			(($(window).height() < $(document).height()) ? $(".anchor").show(function() { $(".anchorLink").anchorAnimate(); }) : $(".anchor").hide());
		},	
			
		formFieldFocus: function(element)
		{
			$(element).addClass("selected");
		
			if($(element).nextAll(".help:visible").size() > 0) 
			{	
				return;
			}
			else
			{
				if($(element).val()) 
				{
					SarahBaker.Page.formFieldHelpShow(element,".pass","success");			
				}
				else
				{
					SarahBaker.Page.formFieldHelpHide(element,"success");
					SarahBaker.Page.formFieldHelpShow(element,".info","");
				}
			}
		},	
	
		formFieldBlur: function(element)
		{
			$(element).removeClass("selected");
		
			if($(element).val()) 
			{
				SarahBaker.Page.formFieldHelpHide(element,".pass","success");
			
				if($(element).attr("id") == "email") 
				{
					if(!$(element).val().match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.@-]+\.[A-Za-z]{2,6}$/)) 
					{
						SarahBaker.Page.formFieldHelpShow(element,".fail","error");
					
						return;
					}
				}
						
				SarahBaker.Page.formFieldHelpShow(element,".pass","success");
			}
			else
			{
				SarahBaker.Page.formFieldHelpHide(element,"error success");
			}
		},
		
		checkKeyInput: function(event) 
		{
			if(event.keyCode >= 48 && event.keyCode <= 57 && !event.altKey && !event.ctrlKey && !event.shiftKey) 
			{	
				return true;
			}
			
			if(event.keyCode >= 65 && event.keyCode <= 90 && !event.altKey && !event.ctrlKey) 
			{
				return true;
			}
			
			if(event.keyCode == 0 || event.keyCode == 8 || event.keyCode == 46) 
			{
				return true;
			}
			
			return false;
		},
		
		formFieldKeyUp: function(element,event)
		{
			if(SarahBaker.Page.checkKeyInput(event)) 
			{
				SarahBaker.Page.formFieldHelpHide(element,".fail","error");
				SarahBaker.Page.formFieldHelpShow(element,".checking","");
	
				setTimeout(function() 
				{
					SarahBaker.Page.formFieldHelpHide(element,".checking","");
							
					if(!$(element).val().match(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.@-]+\.[A-Za-z]{2,6}$/)) 
					{
						SarahBaker.Page.formFieldHelpShow(element,".fail","error");
					}
					else
					{
						SarahBaker.Page.formFieldHelpShow(element,".pass","success");
					}
				}, 
				1000);
			}
			
			($(element).val($(element).val().replace(/\W+.@/,"")));
		},
		
		clearFormFields: function()
		{	
			$(".thankyou").hide();
			$(".fail").hide();
		
			$("input").each(function(i,element) 
			{
				$(element).nextAll().hide();
				$(element).nextAll(".clear").show();
				$(element).removeClass("success");
				$(element).removeClass("error");
				$(element).val(""); 
			});
			
			$("textarea").each(function(i,element) 
			{
				$(element).nextAll().hide();
				$(element).nextAll(".clear").show();
				$(element).removeClass("success");
				$(element).removeClass("error");
				$(element).val(""); 
			});
			
			$("select").find("option:first").attr("selected","selected");
		},
		
		formFieldsValidate: function() 
		{
			$("input").each(function(i,element) 
			{
				if(!$(element).val()) 
				{
					SarahBaker.Page.formFieldHelpShow(element,".fail","error");
				}
			})
			
			$("textarea").each(function(i,element) 
			{
				if(!$(element).val()) 
				{
					SarahBaker.Page.formFieldHelpShow(element,".fail","error");
				}
			})
				
			if($(".fail:visible").size() > 0) 
			{
				return false;
			}
			else
			{	
				return true;
			}
		},				
	
		formFieldHelpShow: function(element,divClass,elementClass)
		{	
			$(element).nextAll().hide();
			$(element).nextAll(".clear").show();
			$(element).nextAll(divClass).show();
			$(element).addClass(elementClass);
		},
		
		formFieldHelpHide: function(element,elementClass)
		{	
			$(element).nextAll().hide();
			$(element).nextAll(".clear").show();
			$(element).removeClass(elementClass);
		},
		
		updateClicks: function(id)
		{	
			$.ajax(
			{
		   		type: "POST",
		   		url: "functions/update-clicks.php",
		   		data: "id=" + escape(id),
		   		success: function(data,textStatus)
		   		{
		   			SarahBaker.Page.showMessage(textStatus);
		   		},
		   		error: function(XMLHttpRequest,textStatus,errorThrown)
		   		{
		   			SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
		   		}
			});
		},
		
		addBookmark: function(title,url)
		{
			if(window.sidebar)
			{	
				window.sidebar.addPanel(title,url,"");
			}
			else if(window.opera && window.print)
			{
				var elem = document.createElement("a");
				elem.setAttribute("href",url);
				elem.setAttribute("title",title);
				elem.setAttribute("rel","sidebar");
				elem.click();
			}
			else if(document.all)
			{
				window.external.AddFavorite(url,title);
			}
		},
		
		showGoogleMap: function()
		{
			var latlng = new google.maps.LatLng(52.94389,-8.03551);
			    
			var options = 
			{
				zoom:11,
				center:latlng,
				mapTypeId:google.maps.MapTypeId.ROADMAP
			};
			
			SarahBaker.Page.map = new google.maps.Map($("#map").get(0),options);
			
			var infowindow = new google.maps.InfoWindow(
			{
				content: "We're Here!"
			});
			
			var marker = new google.maps.Marker(
			{
				position: latlng,
				map: SarahBaker.Page.map,
				title: "Sarah Baker Cookery School"
			});
			
			google.maps.event.addListener(marker,"click",function() 
			{
				infowindow.open(SarahBaker.Page.map,marker);
			});			
		},
		
		showMessage:function(message)
		{
			alert(message);
		}
	},
	
	Store:
	{
		continueShopping: function()
		{
			SarahBaker.Store.showWhatsOn();
		},
		
		bookingConfirmation: function(invoice)
		{
			$.ajax(
			{
		   		type: "POST",
		   		url: "/functions/booking-confirmation.php",
		   		data: "invoice=" + escape(invoice),
		   		success: function(data,textStatus)
		   		{
		  		},
		   		error: function(XMLHttpRequest,textStatus,errorThrown)
		   		{
		   			SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown + "\n\nPlease Contact Us");
				}
			});
			
			return false;
		},
		
		clearCart: function()
		{
			$.ajax(
			{
		   		type: "POST",
		   		url: "/functions/clear-cart.php",
		   		success: function(data,textStatus)
		   		{
		   			$(".btnClearCart").fadeOut("slow").slideUp();
					$(".btnUpdateCart").fadeOut("slow").slideUp();
					$(".btnCheckOut").fadeOut("slow").slideUp();
					$(".btnContinueShopping").fadeOut("slow").slideUp();
					$(".price").fadeOut("slow").slideUp();
					$("fieldset").fadeOut("slow").slideUp(function()
					{
						SarahBaker.Store.showStore();
					});
				},
		   		error: function(XMLHttpRequest,textStatus,errorThrown)
		   		{
		   			SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
		   		}
			});
		},
		
		deleteItem: function(key)
		{	
			$.ajax(
			{
		   		type: "POST",
		   		url: "/functions/delete-item.php",
		   		data: "key=" + escape(key),
		   		success: function(data,textStatus)
		   		{	
					$.ajax(
					{
						type: "POST",
						url: "/functions/count-items.php",
						success: function(data,textStatus)
						{
							if(parseInt(data) == 0)
							{
								$(".btnClearCart").fadeOut("slow").slideUp();
								$(".btnUpdateCart").fadeOut("slow").slideUp();
								$(".btnCheckOut").fadeOut("slow").slideUp();
								$(".btnContinueShopping").fadeOut("slow").slideUp();
								$(".price").fadeOut("slow").slideUp();
								$("fieldset").fadeOut("slow").slideUp(function()
								{
									SarahBaker.Store.showStore();
								});
							}
							else
							{
								$("#item_" + key).fadeOut("slow").slideUp();
							}
						},
						error: function(XMLHttpRequest,textStatus,errorThrown)
						{
							SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
						}
					});
				},
		   		error: function(XMLHttpRequest,textStatus,errorThrown)
		   		{
		   			SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
		   		}
			});
		},
		
		updateCart: function(cart_keys)
		{	
			var keys = cart_keys.split(",");
			
			for(var i in keys)
			{		
				var tmp = $("#txtQuantity" + keys[i]).val();
				
				if(tmp == "" || tmp == 0)
				{
					SarahBaker.Store.deleteItem(keys[i]);
				}
				else
				{
					$.ajax(
					{
		   				type: "POST",
		   				url: "/functions/update-cart.php",
		   				data: "key=" + escape(keys[i]) + "&quantity=" + escape(tmp),
		   				success: function(data,textStatus)
		   				{
		   					SarahBaker.Store.showStore();
		   				},
		   				error: function(XMLHttpRequest,textStatus,errorThrown)
		   				{
		   					SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
		   				}
					});
				}
			}
		},
		
		countPlaces: function(key,quantity)
		{
			$.ajax(
			{
				type: "POST",
				url: "/functions/count-places.php",
				data: "key=" + escape(key),
				success: function(data,textStatus)
				{
					if(parseInt(quantity) > parseInt(data))
					{
						SarahBaker.Page.showMessage("Sorry, this Course only has " + data + " place" + ((data > 1) ? "s" : "") + " available for the selected Date / Time.");
						
						$("#txtQuantity" + key).val(data);
					}				
				},
				error: function(XMLHttpRequest,textStatus,errorThrown)
				{
					SarahBaker.Page.showMessage(XMLHttpRequest.statusText + "\n\n" + textStatus + "\n\n" + errorThrown);
				}
			});
		},
		
		showWhatsOn: function()
		{
			window.location = "/whats-on/";
		},
		
		showStore: function()
		{
			window.location = "/whats-on/store/";
		},
		
		showCancellation: function()
		{
			window.location = "/whats-on/cancelled/";
		}
	},
	
	CMS: 
	{
		init: function()
		{		
			if($("a.gallery").length)
			{
				$("a.gallery").fancybox(
				{
					"titlePosition": "over",
					"transitionIn": "fade",
					"transitionOut": "fade",
					"centerOnScroll": true,
					"onComplete":function() 
					{
						$("#fancybox-wrap").hover(function() 
						{
							$("#fancybox-title").show();
						}, 
						function() 
						{
							$("#fancybox-title").hide();
						});
					}
				});
			}
			
			if($("textarea").length)
			{
				SarahBaker.CMS.loadWYSIWISControls();
			}
						
			$("#add_course_date").click(function()
			{
				var places = $("#places").val();
				var course_date = $("#new_course_date").val(); 
				
				if(places == null || places == "" || places == 0)
				{
					SarahBaker.Page.showMessage("Please enter the number of Places of the Course first");
				}
				else
				{
					if(course_date == null || course_date == "" || course_date == 0)
					{
						SarahBaker.Page.showMessage("Please enter the Date of the Course");
					}
					else
					{
						$("#new_course_date").val("");
					
						SarahBaker.CMS.addCourseDate(course_date);
					}
				}
			});
			
			$("#edit_add_course_date").click(function()
			{
				var course_date = $("#edit_new_course_date").val(); 
				
				if(course_date == null || course_date == "" || course_date == 0)
				{
					SarahBaker.Page.showMessage("Please enter the Date of the Course");
				}
				else
				{
					$("#new_course_date").val("");
					
					SarahBaker.CMS.addEditCourseDate(course_date);
				}
			});

			$("#places").keyup(function()
			{
				var places = $(this).val();
				
				if(places == 0)
				{
					SarahBaker.Page.showMessage("Courses cannot have 0 Places");
	
					$(this).val("");
				}
				else
				{	
					places = places.replace(/[^0-9]/g,"");
						
					$(this).val(places);
				}
			});
			
			if($("#new_course_date,#edit_new_course_date").length)
			{
				$("#new_course_date,#edit_new_course_date").datepicker(
				{ 
					dateFormat: "yy/mm/dd", 
					inline: true, 
					changeMonth: true, 
					changeYear: true 
				});
			}
		},
		
		loadWYSIWISControls: function()
		{
			$("textarea").tinymce(
			{
				elements: 'abshosturls',
				script_url: "/js/tiny_mce/tiny_mce.js",
				relative_urls : false,
				remove_script_host : false,
				document_base_url : "http://www.sarahbaker.ie/",
				theme: "advanced",
				plugins:"safari,spellchecker,preview,paste,advimage,advlink,media,searchreplace,xhtmlxtras,print",
				theme_advanced_buttons1:"newdocument,|,search,replace,|,charmap,|,print,|,image,|,undo,redo,|,indent,outdent,|,preview,spellchecker,|,cleanup,code,help",
				theme_advanced_buttons2:"cut,copy,paste,pastetext,pasteword,removeformat,abbr,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontsizeselect,|,bold,italic,underline,strikethrough,|,bullist,link,unlink",
				theme_advanced_buttons3:"",
				theme_advanced_buttons4:"",
				theme_advanced_toolbar_location:"top",
				theme_advanced_toolbar_align:"left",
				theme_advanced_resizing:true,
				theme_advanced_disable:"",
				theme_advanced_font_sizes:"10px,12px,14px",
				theme_advanced_statusbar_location:"bottom",
				spellchecker_languages:"+English=en",
				verify_html:true,
				file_browser_callback:tinyupload,
				disk_cache:true,
    			debug:false,
    			gecko_spellcheck:true
			});
		},
		
		loadCourseDates: function(id)
		{
			$("#loading_c_dates").show();
			
			$.ajax(
			{
				url: "../functions/get-course-dates.php?id=" + id,
				cache: false,
				success: function(dates)
				{	
					$("#course_dates").append(dates);
					$("#loading_c_dates").hide();
				}
			});
		},
			
		addCourseDate: function(date)
		{
			$("#course_dates ul").append($("<li/>").attr(
			{
				"id": date
			}).append($.datepicker.formatDate('DD, d M, yy',new Date(date)) + " ").append($("<input/>").attr(
			{
				"type": "hidden",
				"name": "course_dates[]",
				"value": date
			})).append($("<a/>").attr(
			{
				"href": "javascript:void(0);",
				"title": "Click here to remove this Date",
				"onclick": "parent.SarahBaker.CMS.removeCourseDate('" + date + "');"
			}).append($("<img/>").attr(
			{
				"src":"/media/delete.png",
				"alt":"Remove this Date"
			}).css("border","0px").css("verticalAlign","middle").css("marginBottom","4px"))));
		},
		
		addEditCourseDate: function(date)
		{
			$("#course_dates ul").append($("<li/>").attr(
			{
				"id": date
			}).append($("<input/>").css(
			{
				"textAlign":"center",
				"width":"37px"
			}).attr(
			{
				"type": "text",
				"name": "course_date_places[]",
				"value": "16" 
			})).append(" | ").append($.datepicker.formatDate('DD, d M, yy',new Date(date)) + " ").append($("<input/>").attr(
			{
				"type": "hidden",
				"name": "course_dates[]",
				"value": date
			})).append($("<a/>").attr(
			{
				"href": "javascript:void(0);",
				"title": "Click here to remove this Date",
				"onclick": "parent.SarahBaker.CMS.removeCourseDate('" + date + "');"
			}).append($("<img/>").attr(
			{
				"src":"/media/delete.png",
				"alt":"Remove this Date"
			}).css("border","0px").css("verticalAlign","middle").css("marginBottom","4px"))));
		},		
		
		removeCourseDate: function(date)
		{
			$("#course_dates ul li[id=" + date + "]").remove();
		}
	}
};