var kk = (function($){
  //cache main elements
  var $body = $(document.body),
      $menu = $('#menu'),
      $home = $('#home'),
      $staff = $('#staff'),
      $schedule = $('#schedule'),
      $nutrition = $('#nutrition'),
      $tuition = $('#tuition'),
      $contact = $('#contact'),
      $textcontent = $('#text-content'),
			$form = $('form.parent-login-form'),
		  isloggedin = false;

	function getLoginStatus(){
		return isloggedin;
	}
	
	function setLoginStatus(st){
		isloggedin = st;
	}
	
	function getCaption(page){
		var cap_map = {
			home :"A day at the beach",
			overview:"Lining up to play a game",
			tuition:"Graduation Day!",
			policies:"There's always lots to do at recess",
			photos:"At play during recess",
			staff:"Our staff",
			parents:"Getting ready for a field trip",
			contact:"Contact us!"
		};
		
		return cap_map[page];
	}
		
  function _xhr_request(page,opt){
		if (opt && opt["page"] != undefined){
			//alert('option passed in for page')
			//page = opt["page"];
		}
		
		var src = "../images/" + page + ".jpg";
		var cap = getCaption(page);
	 	page = "/html/"+page + ".html";
	
		$.ajax({
      url:page,
      success:function(data){
        $textcontent.html(data);				
				$("#photo img").attr("src",src);
				$("#photo .caption").html(cap);
      }
    });
  };

	//init history plugin
	$.history.init(function(url){
		url = (url == "") ? "home" : url
		_xhr_request(url);
		var li = $("li.nav[data-page=" + url + "]");
		setTabs(li);
	});
	
	//login form
	$form.live('submit',function(){
		var user = $('form.parent-login-form input.name').val();
		var pw = $('form.parent-login-form input.pw').val();
		/*var uri = 'http://' + user + ':' + pw + '@www.kidskollege.com/parents/index.html';for htaccess login over ajax*/
		var qry = $(this).serialize();
		$.ajax({
			type:'GET',
			data:qry,
			url:'../parents/parents.php',
			success:function(data){
				//work around until i can send actual server status over ajax
				if (data == 0){
					
				}else{
					//kk.isloggedin = true; //client-side for now
					setLoginStatus(true);
					$('#text-content').load('../parents/parents.php?' + qry);
				}
			},
			error:function(jqXHR, textStatus, errorThrown){
				alert('There was an error: ' + errorThrown)
			}
		});
		return false;
	});
	
	function setTabs(li){		
		$("ul#menu li.nav").each(function(){
			$(this).removeClass("active");
		});
		$(li).addClass("active");
	}
	
	//document.ready event
	$(document).ready(function(){
		$menu.delegate("li.nav","click", function(){
			setTabs(this);
	    var page = $(this).attr('href'); //user clicks anchor
			page = page == undefined ? $(this).attr('data-page'): page; //user clicks li
			page = page.replace(/^.*#/,'');
			//update history
			$.history.load(page);
			return false;
	  });
	});
	
	return {
		getLoginStatus:getLoginStatus
	}
	
})(jQuery);
