// from http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript
(function($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	};
})(jQuery);
function divSlide(div_id, setHeight, setTop, timeMs) {
	$(div_id).stop().animate({
		height: setHeight,
		top: setTop
	}, {
		duration: timeMs
	});
	//  $('#news-panel-top-border').stop().animate({
	//      top: setTop
	//    }, {
	//      duration: timeMs
	//    }
	//  );
}
function divExpand(div_id) {
	$(div_id).stop().animate({
		height: "100%"
	}, {
		duration: 500
	});
}
function newsPanelSlideIn() {
	divSlide("#news-panel", "102px", "-104px", 500);
	divSlide("#news-panel-top-border", "102px", "-104px", 500);
}
function newsPanelSlideOut() {
	divSlide("#news-panel", "42px", "-44px", 500);
	divSlide("#news-panel-top-border", "42px", "-44px", 500);
}
function issuesPanelSlideOut() {
	divSlide("#news-panel-top-border", "42px", "-44px", 500);
}
function loginSlideIn() {
	if (is_admin) divSlide("#login_form", "220px", "-160px", 500);
	else divSlide("#login_form", "280px", "-220px", 500);
}
function loginSlideOut() {
	divSlide("#login_form", "50px", "8px", 500);
}
function f_setLogin() {
	var nlreq_form = $('#nlreq_form');
	$('#login_form').hover(loginSlideIn, loginSlideOut);
	if (!is_admin) { // is_admin is a global variable set in head.php
		// Launch MODAL BOX if the Login Link is clicked
		// When the form is submitted
		$("#status > form").submit(function() {
			$('#login_submit').hide();
			$('#ajax_loading').show();
			var str = $(this).serialize();
			$.ajax({
				type: "POST",
				url: "do-login.php",
				data: str,
				success: function(msg) {
					$("#status").ajaxComplete(function(event, request, settings) {
						$('#login_submit').show();
						$('#ajax_loading').hide();
						if (msg == 'OK') {
							var login_response = "<div style='padding:20px;'>Login Successful : Please wait! Loading Admin content..</div>";
							$('a.modalCloseImg').hide();
							$('#simplemodal-container').css("width", "300px");
							$('#simplemodal-container').css("height", "120px");
							$(this).html(login_response);
							// After 3 seconds reload the page
							setTimeout(window.location.reload(), 3000);
						} else {
							var login_response = msg;
							$('#login_response').html(login_response);
						}
					});
				} // end sucess function
			}); // end ajax
			return false;
		}); // end submit
		if (nlreq_form.length) {
			// form validator for newsletter request form
			nlreq_form.validate({
				rules: {
					first_name: "required",
					last_name: "required",
					email_address: {
						required: true,
						email: true
					}
				}
			});
			$("#nlreq_form_area > form").submit(function() {
				if (nlreq_form.valid()) {
					$('#nlreq_submit').hide();
					$('#nlreq_ajax_loading').show();
					$.ajax({
						cache: false,
						data: {
							first_name: $('#first_name').val(),
							last_name: $('#last_name').val(),
							email_address: $('#email_address').val()
						},
						type: "POST",
						dataType: "html",
						url: "include/add_nlreq.php",
						success: function(msg) {
							$("#nlreq_form_area").ajaxComplete(function(event, request, settings) {
								if (msg == 'OK') {
									var nlreq_response = "<div style='padding:20px; color:#439644'>Thank you for your interest!<br><br></div>";
								} else {
									var nlreq_response = "<div style='padding:20px;color:red'>We are sorry but some error has occured! <br><br>Your request could not be completed.. Please try again later..<br><br></div>";
								}
								$(this).html(nlreq_response);
							});
						} // end sucess function
					}); // end ajax
				}
				return false;
			}); // end submit
		}
	}
}
function f_setContactForm() {
	// when contact form is clicked
	$("#btnSubmit_contact").click(function() {
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var zipReg = /^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/;
		var phoneReg = /^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$/;
		var v1 = $("#form_emailTo").val();
		var v2 = $("#first_name").val();
		var v3 = $("#last_name").val();
		var v4 = $("#street_address").val();
		var v5 = $("#city").val();
		var v6 = $("#zip").val();
		var v7 = $("#phone").val();
		var v8 = $("#state").val();
		var v9 = $("#about_you").val();
		if (v1 === '') {
			$("#form_emailTo").after('<span class="error">Please enter your email id.</span>');
			hasError = true;
		} else if (!emailReg.test(v1)) {
			$("#form_emailTo").after('<span class="error">Please enter a valid email id.</span>');
			hasError = true;
		}
		if (v2 === '') {
			$("#first_name").after('<span class="error">Please enter your First Name.</span>');
			hasError = true;
		}
		if (v3 === '') {
			$("#last_name").after('<span class="error">Please enter your Last Name.</span>');
			hasError = true;
		}
		if (v4 === '') {
			$("#street_address").after('<span class="error">Please enter your Street address.</span>');
			hasError = true;
		}
		if (v5 === '') {
			$("#city").after('<span class="error">Please enter your City Name.</span>');
			hasError = true;
		}
		if (v6 === '') {
			$("#zip").after('<span class="error">Please enter your ZIP</span>');
			hasError = true;
		} else if (!zipReg.test(v6)) {
			$("#zip").after('<span class="error">Please enter a valid ZIP code</span>');
			hasError = true;
		}
		if (v7 === '') {
			$("#phone").after('<span class="error">Please enter your phone number</span>');
			hasError = true;
		} else if (!phoneReg.test(v7)) {
			$("#phone").after('<span class="error">Please enter a valid phone number.</span>');
			hasError = true;
		}
		if (v8 === '') {
			$("#state").after('<span class="error">Please choose your state.</span>');
			hasError = true;
		}
		if ($('#volunteer').is(':checked')) {
			v10 = '1';
		} else {
			v10 = '0';
		}
		if (hasError === false) {
			$(this).hide();
			$("#sendEmail li.buttons").append('<img src="images/loading.gif" alt="Sending" id="loading" />');
			$.post("sendcontact_mail.php", {
				f1: v1,
				f2: v2,
				f3: v3,
				f4: v4,
				f5: v5,
				f6: v6,
				f7: v7,
				f8: v8,
				f9: v9,
				f10: v10
			}, function(data) {
				$("#sendEmail_contact_form").slideUp("normal", function() {
					$("#sendEmail_contact_form").before('<br><br><p>' + data + '</p>');
				});
			});
		}
		return false;
	});
}
$(document).ready(function() {
	$('#home_link').click(function() {
		window.location = 'index.php';
	});
	f_setLogin();
	$("#emailTo").autoclear();
	$("#submit").click(function() {
		$(".error").hide();
		var hasError = false;
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		var emailToVal = $("#emailTo").val();
		if (emailToVal === '') {
			$("#errmsg").html('<span class="error">Please enter your email id.</span>');
			hasError = true;
		} else if (!emailReg.test(emailToVal)) {
			$("#errmsg").html('<span class="error">Please enter a valid email id.</span>');
			hasError = true;
		}
		if (hasError === false) {
			$(this).attr('disabled', 'disabled');
			var v1 = $("#emailTo").val();
			$.post("sendmail.php", {
				f1: v1
			}, function(data) {
				$("#errmsg").html('<span class="error">' + data + '</span></p>');
			});
		}
		return false;
	});
	if ($("#sendEmail_contact_form").length) {
		f_setContactForm();
	}
	if ($("#banner").length) {
		// special for home page only
		jQuery.preLoadImages("images/banner_1.png", "images/banner_2.png");
		var startSlide = 1;
		// Get slide number if it exists
		if (window.location.hash) {
			startSlide = window.location.hash.replace('#', '');
		}
		// Initialize Slides
		$('#slides').slides({
			preload: false,
			preloadImage: 'img/loading.gif',
			generatePagination: true,
			play: 5000,
			pause: 8000,
			hoverPause: true,
			// Get the starting slide
			start: startSlide,
			animationComplete: function(current) {
				// Set the slide number as a hash
				window.location.hash = '#' + current;
			}
		});
		var mfull_ht = $('#issues_container').css('height');
		if (mfull_ht1 == '496px') {
			$('#expand_more_issues').hide();
		} else {
			if (!is_admin) $('#issues_container').height(304);
			$('#expand_more_issues').click(function() {
				var mht = $('#issues_container').css('height');
				if (mht == '304px') {
					$('#btn_expand_issues').attr('src', 'images/btn-round_up.png');
					$('#issues_container').stop().animate({
						height: mfull_ht
					}, {
						duration: 1500
					});
				} else {
					$('#btn_expand_issues').attr('src', 'images/btn-round_down.png');
					$('#issues_container').stop().animate({
						height: "304"
					}, {
						duration: 1500
					});
				}
			});
		}
		var mfull_ht1 = $('#photos_container').css('height');
		if (mfull_ht1 == '496px') {
			$('#expand_more_photos').hide();
		} else {
			if (!is_admin) $('#photos_container').height(496);
			$('#expand_more_photos').click(function() {
				var mht = $('#photos_container').css('height');
				if (mht == '496px') {
					$('#btn_expand_photos').attr('src', 'images/btn-round_up.png');
					$('#photos_container').stop().animate({
						height: mfull_ht1
					}, {
						duration: 1500
					});
				} else {
					$('#btn_expand_photos').attr('src', 'images/btn-round_down.png');
					$('#photos_container').stop().animate({
						height: "496"
					}, {
						duration: 1500
					});
				}
			});
		}
	} // end for home page only
	f_setComments();
	//  $('#keywords').blur(function () {
	//    if (!$(this).val()) {
	//      $(this).css('background','white url(http://www.google.com/coop/images/google_custom_search_watermark.gif) no-repeat 0% 50%');
	//    }
	//  });
	//  
	//  $('#keywords').focus(function () {
	//    $(this).css('background','');
	//  });
	//
	//  $('#news-panel').hover(newsPanelSlideIn,newsPanelSlideOut);
	//  $('#login_form').hover(loginSlideIn,loginSlideOut);
	//    
	//  // call function that sets login form
	//  f_setLogin();
	//    
	//    // setup show comments button and submit comment form on topic_toolbar
	//
	//  $.timedInterval(12000,function () {
	//    rotateClips();
	//  });
	//  
	//  $('#keywords').css('outline','0 none');
	//  $('#keywords').blur();
});
function f_setComments() {
	$(".btnComnt").click(function() {
		$clicked = $(this);
		var idToLoad = $clicked.attr("id").split('__');
		if ($("#divComnt__" + idToLoad[1]).is(":visible")) {
			$(".divComnt").hide("slow");
			$(".divComnt").html("<img src='images/spinner.gif' width='16' height='16' alt='Loading' /> Loading..");
		} else {
			$(".divComnt").hide("fast");
			$(".divComnt").html("<img src='images/spinner.gif' width='16' height='16' alt='Loading' /> Loading..");
			$("#divComnt__" + idToLoad[1]).show("fast");
			$("#divComnt__" + idToLoad[1]).delay(100);
			$("#divComnt__" + idToLoad[1]).css("display", "inline-block");
			$.ajax({
				cache: false,
				data: {
					cid: idToLoad[1]
				},
				dataType: "text",
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("Error: Failed to load comments\n" + XMLHttpRequest.responseText + "\n" + textStatus + "\n" + errorThrown);
					$("#divComnt__" + idToLoad[1]).hide();
				},
				success: function(data, textStatus) {
					$("#divComnt__" + idToLoad[1]).html(data);
					f_setComntForm(idToLoad[1]);
				},
				type: "GET",
				url: "include/get_comnt_view.php"
			});
		}
	});
}
function f_setComntForm(mNewsId) {
	var comnt_form = $('#comnt_form');
	if (comnt_form.length) {
		// form validator for newsletter request form
		comnt_form.validate({
			rules: {
				first_name: "required",
				comments: "required",
				email_address: {
					required: true,
					email: true
				}
			}
		});
		$("#comnt_form_area > form").submit(function() {
			if (comnt_form.valid()) {
				$('#comnt_submit').hide();
				$('#comnt_ajax_loading').show();
				$.ajax({
					cache: false,
					data: {
						first_name: $('#first_name').val(),
						comment: $('#comments').val(),
						cid: mNewsId,
						email_address: $('#email_address').val()
					},
					type: "POST",
					dataType: "html",
					url: "include/add_comnt.php",
					success: function(msg) {
						$("#comnt_form_area").ajaxComplete(function(event, request, settings) {
							if (msg == 'OK') {
								var comnt_response = "<div style='padding:20px; color:#439644'>Thank you for your feedback!<br><br></div>";
							} else {
								var comnt_response = "<div style='padding:20px;color:red'><br>We are sorry but some error has occured! <br><br>Your request could not be completed.. Please try again later..<br><br></div>";
							}
							$(this).html(comnt_response);
							setTimeout(window.location.reload(), 5000);
						});
					} // end sucess function
				}); // end ajax
			}
			return false;
		}); // end submit
	}
}

