$(document).ready(function(){
	Site_Path = 'http://www.westernbagel.com/';
	Secure_Path = 'https://www.westernbagel.com/';


	left_bar_container_h = $('.left_bar_container').height()
	content_container_h = $('.content_container').height()

	if (content_container_h > left_bar_container_h) {
		$('.left_bar_container').height(content_container_h)
	} else {
		$('.content_container').height(left_bar_container_h)
	}

	$('img').css('border',0)


				$(document).bind("mousedown", function(event) {
					if ($(event.target).attr('id') != 'log_in') {
					if ( ($(event.target).parents("#login_box").size() == 0)  ){
						$('#login_box').hide()
					}
				}
				})

	/* HEADER */
cookie_name = 'CustomerID';
if ($.cookie(cookie_name) )  {
	var return_parts = $.cookie(cookie_name).split("|")
			$('#sign_up_header').hide()
			$('#log_in_header').hide()
			$('#log_out_header').show()
			if (return_parts[1] != '') {
				$('#log_out').html('(Not '+ return_parts[1] + '?)')
			} else {
				$('#log_out').html('Log Out')
			}

} else {
			$('#sign_up_header').show()
			$('#log_in_header').show()
			$('#log_out_header').hide()
}


	$('#log_in').click(function(e) {
		e.preventDefault()
		$(this).blur()
		$('#login_box').show()
	})
	/* LOG IN BOX */
	login_position = $('#log_in').position();
	$('#login_box').css({'left':login_position.left-316+'px'})
	$('#login_forgot_password').click(function() {
		document.location = Site_Path+'forgot_password.php'
	})


	$('#login_sign_up').click(function() {
		document.location = Site_Path+'sign_up.php'
	})
	$('#login_box_close').click(function() {
		$('#login_box').hide()
	})
	$('#login_box_button').click(function() {
		this_error = 0;
		$("#error_row").hide()
		$("#error_row_pass").hide()

		$('#login_form').find("input[id^='LoginEmailPop']").each(function() {
			this_id = $(this).attr('id')
			is_required = $(this).attr('required')
			if (( $(this).val() == '') && (is_required == 1)) {
				$('#login_form').find("[id^='"+this_id+"']").addClass('error')
				this_error = 1;
			} else {
				$('#login_form').find("[id^='"+this_id+"']").removeClass('error')
			}

			var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
			var emailaddressVal = $("input[id='LoginEmailPop']").val();

			if ( emailaddressVal == '') {
				$("[id^='LoginEmailPop']").addClass('error')
				this_error = 1;
			} else {
				if(!emailReg.test(emailaddressVal)) {
					$("#login_error_row").slideDown('fast')
		 			$("#login_error_row_text").html('Email Address Not A Valid Email').css({'background':'none', 'padding':'0'})
					$("[id^='LoginEmailPop']").addClass('error')
					this_error = 1;
				} else {
					$("#login_error_row").hide()

					$("[id^='LoginEmailPop']").removeClass('error')
				}
			}
		})

		$('#login_form').find("input[id^='LoginPasswordPop']").each(function() {
			this_id = $(this).attr('id')
			is_required = $(this).attr('required')
			if (( $(this).val() == '') && (is_required == 1)) {
				$('#login_form').find("[id^='"+this_id+"']").addClass('error')
				this_error = 1;
			} else {
				$('#login_form').find("[id^='"+this_id+"']").removeClass('error')
			}
		})
		if (this_error == 0) {


			$('#login_box_button').addClass('saving').html('...').css({'color':'#333333'})
			$.post('/cart_functions/login.php?Log_In=1', $('#login_form').serialize(), function(data){
				$("#login_box_button").removeClass('saving').html('Log in').css({'color':'#000'})
				data = $.trim(data)
				var isgood = data.split("|")
				if (isgood[0] == 'Bad') {
					if (isgood[1] == 'Password'){
						$("#error_row_pass").slideDown('fast')
						$("#error_row_pass_text").html("Your Password is incorrect. Please Re-Enter your Password").css({'background':'none', 'padding':'0'})
					}
					if (isgood[1] == 'EmailAddress'){
						$("#login_error_row").slideDown('fast')
						$("#login_error_row_text").html("We do not have an Account with that Email Address.").css({'background':'none', 'padding':'0'})
					}
 				} else {


					var return_data_parts = $.trim(data).split("~")
					session_cookie = return_data_parts[0]
					update_cookie_data(session_cookie)

					customer_cookie = return_data_parts[1]
					update_customer_data(customer_cookie)
					$('#login_box').hide()

					// wholesale user
					if (isgood[6] == 'WS') {
						// refresh page.
						window.location.reload();
					}
				}
		}) // end post
		}

	})

	$('#log_out').click(function(e) {
		e.preventDefault()
		var cookie_name = 'CustomerID';
		var options = { path: '/', expires: 0 };
		$.cookie(cookie_name, '0', options);

		var cookie_name = 'SessionID';
		var options = { path: '/', expires: 0 };
		$.cookie(cookie_name, '0', options);

		update_customer_data(0)

	})


	/*******************/
	/* MAIN NAVIGATION */
	/*******************/
	$("li[id^='main_top_nav_']").each(function() {

		if ($(this).attr('go_to_page') != undefined) {
			$(this).click(function(event){
				document.location = Site_Path+$(this).attr('go_to_page')
				event.stopPropagation();
			})
		}
	})

	$("[id^='top_nav_category_']").each(function() {

		if ($(this).attr('go_to_page') != undefined) {
			$(this).click(function(event){
				a = document.location
				b = a.toString()
				c = b.split("#")
				thisPageA = c[0].split('/')
				PageOn = thisPageA[thisPageA.length-1]
//				alert(thisPageA[thisPageA.length-1])

				gotoArray = $(this).attr('go_to_page').split("#")
				PageGoTo = gotoArray[0]

				if (PageGoTo == PageOn) {
					// scroll to
						var ThisCat = gotoArray[1]
						ThisCatWords = ThisCat.split("_")
						NewWords = ''
						//	alert(ThisCatWords.length)
						LastSpace = ThisCatWords.length-1
						for (x=0; x<ThisCatWords.length; x++) {
							NewWords += ThisCatWords[x].substr(0, 1).toUpperCase() + ThisCatWords[x].substr(1)
							if (x != LastSpace) {
								NewWords += ' '
							}
						}
						//alert(NewWords)
						ThisCat = ThisCat.replace("_", " ");
						ThisCat = ThisCat.substr(0, 1).toUpperCase() + ThisCat.substr(1)
						Next = ThisCat.substr(0, 1).toUpperCase() + ThisCat.substr(1)

						//	alert(ThisCat)
						var ThisCat = NewWords
						this_p = $("div[category='"+ThisCat+"']").position()
						//	alert(this_p.top)
						$('.grocery_side_nav_container').stop().animate({'top':this_p.top+20+'px'}, 10)

						$(document).scrollTo( $("div[category='"+ThisCat+"']"), 800 );
						//event.stopPropagation();
				}
//			alert($(this).attr('go_to_page') ) //our_stores.php#bagel_sandwiches
	//		alert(document.location)  //http://www.westernbagel.com/our_stores.php#alternative_bagels
				document.location = Site_Path+$(this).attr('go_to_page')
				event.stopPropagation();
			})
		}
	})
	$("[id^='drop_down_nav']").each(function() {

			if ($(this).attr('go_to_page') != undefined) {
				$(this).click(function(event){

					document.location = Site_Path+$(this).attr('go_to_page')
					event.stopPropagation();
				})
			}
	})
	$(".sub_menu").children().each(function() {
			$(this).hover(
				function() {
					$(this).find('div[id^="top_nav_category_"]').addClass('hover')
				},
				function() {
					$(this).find('div[id^="top_nav_category_"]').removeClass('hover')
				}
			)
	})
	$(".drop_down_2, .top_links, .bottom_links, a , .login_box_bottom_forgot, .login_box_bottom_signin, .login_box_bottom_button").hover(
				function() { $(this).addClass('hover') },
				function() { $(this).removeClass('hover') }
	)
	$("[id='right_button']").each(function() {
		$(this).hover(
				function() { $(this).parent().children().addClass('hover')},
				function() { $(this).parent().children().removeClass('hover') }
		)
	})

	/***********************/
	/* END MAIN NAVIGATION */
	/**********************/


	/* GET PAGE LINK */
		$('.top_links, .bottom_links').each(function() {
			$(this).click(function(event){
				if ($(this).attr('site_page_id') != undefined) {
						event.stopPropagation();
					$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('site_page_id') }, function(data){
//				alert(data)
				if (data) {
						document.location = $.trim(data)
						}
					});
						event.stopPropagation();
				} else {
				}
			})
		})
		/* GET PAGE LINK
		$('a').each(function() {
			$(this).click(function(event){
				if ($(this).attr('site_page_id') != undefined) {
					$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('site_page_id') }, function(data){

						document.location = $.trim(data)
					});
						event.stopPropagation();
				} else {
				}
			})
		})
		*/
	/* BUTTON LINKS */
	$("[id^='buttons_']").each(function() {
			$(this).click(function(event){
				if ($(this).attr('site_page_id') != undefined) {
					$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('site_page_id') }, function(data){

						document.location = $.trim(data)
					});
						event.stopPropagation();
				} else {
				}
			})
	})
	/* GET PAGE LINK */
		$('.bottom_button_container').each(function() {
			$(this).hover(
				function() {

					$(this).find('#button_bottom_text').addClass('hover')
				},
				function() {
					$(this).find('#button_bottom_text').removeClass('hover')
				}
			)
			$(this).click(function(event){
				event.stopPropagation();
				event.preventDefault()

				if ($(this).attr('site_page_id') != undefined) {
					$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('site_page_id') }, function(data){

				document.location = $.trim(data)
					});
						event.stopPropagation();
				} else {
				}
			})
		})
/* GET PAGE LINK */
		$('.bottom_link_only').each(function() {
			$(this).click(function(event){

				if ($(this).attr('link_type') == 'Page') {
					if ($(this).attr('link_to') != undefined) {
						$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('link_to') }, function(data){
							document.location =  $.trim(data)
						});
							event.stopPropagation();
					} else {
					}
				} else {
					if ($(this).attr('site_page_id') != undefined) {
						$.post("/global_includes/get_page_link.php", { SitePageID:$(this).attr('site_page_id') }, function(data){
							document.location = $.trim(data)
						});
							event.stopPropagation();
					} else {
					}
				}
			})
		})


	/***********************/
	/*   COOKIE FUNCTIONS  */
	/**********************/

	var cookie_name = 'SessionID';
	var options = { path: '/', expires: 100 };
	var site_page_id = $('#container').attr('site_page_id');
	var product_id = $('#container').attr('product_id');
	var page_url = window.location.pathname;

	$.post("/cart_functions/set_session_cookie.php", {PageURL: page_url, SitePageID: site_page_id, ProductID: product_id}, function(data){
			return_data_parts = $.trim(data).split("~")
			if (data == 0) {
				/* REFRESH COOKIE FOR ANOTHER 100 DAYS */
				$.cookie('SessionID', $.cookie(cookie_name), options);
			} else {
					session_cookie = return_data_parts[0]
					update_cookie_data(session_cookie)

					customer_cookie = return_data_parts[1]
					update_customer_data(customer_cookie)

			}


	});

	/* IF COOKIE IS SET THEN CUSTOMER IS LOGGED IN
	var cookie_name = 'CustomerID';
	if ($.cookie(cookie_name)) {
	//$("a[id^='login']").html('LOG OUT')
	//alert($.cookie(cookie_name))
		if ($.cookie(cookie_name) != '') {
			$("input[id^='CustomerID']").val($.cookie(cookie_name))
			$('#header_right_logged_out').hide()
			$('#header_right_logged_in').show()
		} else {
		$('#header_right_logged_out').show()
		$('#header_right_logged_in').hide()
		}
	} else {
		$('#header_right_logged_out').show()
		$('#header_right_logged_in').hide()
	}
	*/
	/* ALL FORMS */
	$("input").focus(function() {
		$(this).addClass('focus')
	})
	$("input").blur(function() {
		$(this).removeClass('focus')
	})




	$('#main_logo').click(function() {
		document.location = Site_Path+'index.php'
	})
	$('#left_gutter_full').height($('#page_content').height())
	$('#right_gutter_full').height($('#page_content').height())




	/* GROCERY SPECIFIC ? */
	$("[id^='insert_line_']").filter('.package_insert_line').each(function() {
		var number_of_items = $(this).children().size()
		var line_width = $(this).width()

		if ($(this).attr('templateid') != 4) {
			number_of_items = parseInt(number_of_items /2)+1;
			if (number_of_items < 3) {
				number_of_items = 3;
			}
			$(this).attr('line_width', line_width).attr('number_of_items',number_of_items)

			var each_width = parseInt(( (line_width - ((number_of_items-1)*15)) / number_of_items))
			$(this).find("[id='package_insert_container']").each(function() {
				var max_height = parseInt($(this).parent().attr('max_height'))
				this_h = $(this).height()
				if (this_h > max_height) {
					$(this).parent().attr('max_height', this_h)
				}
			})
			//	$(this).find("[id^='package_insert_container']:last").removeClass('right_line')
			//	$('#package_insert_container').append('<div class="package_insert_container_right_line"></div>')
			max_height = $(this).attr('max_height')
			$(this).children("[id='package_insert_container']").width(each_width)
			$(this).children().css({'height':parseInt(max_height)+'px'})
		} else {
			var p = $(this);
			var position = p.position();

			var p = $(this).parent().parent().parent().parent().parent();
			var parent_position = p.position();
			if ((position.left - parent_position.left) < 300) {
				$(this).parent().parent().parent().css({'margin-left':'1px'})
			} else {
				new_width = parseInt($(this).parent().parent().parent().width())
				$(this).parent().parent().parent().css({'width':new_width+1+'px'})
			}
		}
	})



});

/* WHAT NEEDS TO BE PASSED */
/*
	COOKIE 1 WILL EQUAL (SessionID)
	SESSIONID|FIRSTTIME|HASACCOUNT|LOGGEDIN|CARTCOUNT

	COOKIE 2 WILL EQUAL (CustomerID)
	CUSTOMERID|FIRSTNAME
*/
function update_cookie_data(data) {

	var options = { path: '/', expires: 10 };
	var return_parts = data.split("|")
	if (return_parts.length > 1) {
		CartCount = return_parts[4];
		update_cart_data(CartCount)
	} else {
		update_cart_data(0)
	}
	$.cookie('SessionID', data, options);
}



function update_customer_data(data) {

	if (data == 0) {
			$('#sign_up_header').show()
			$('#log_in_header').show()
			$('#log_out_header').hide()
					document.location = Site_Path+'index.php'

	} else if (data != undefined) {
		var return_parts = data.split("|")
		if (return_parts[0] != '0') {
			var options = { path: '/', expires: 10 };
			$.cookie('CustomerID', data, options);
			$('#sign_up_header').hide()
			$('#log_in_header').hide()
			$('#log_out_header').show()
			if (return_parts[1] != '') {
				$('#log_out').html('(Not '+ return_parts[1] + '?)')
			} else {
				$('#log_out').html('Log Out')
			}
		} else {
			$('#sign_up_header').show()
			$('#log_in_header').show()
			$('#log_out_header').hide()
		}


	}

}


function update_cart_data(CartCount) {
	if (CartCount != 0) {
		new_count = '<span style="cart_count_style">('+CartCount+' items)</span>'
		$('#shopping_cart').html('Cart '+new_count)
	} else {
		$('#shopping_cart').html('Cart')
	}
}
