$(document).ready(function() {   
   $('#search input#search_term').val('Search');
   $('input#newsletter_submit').wrap('<p id="nls_wrap"></p>');
   $('#search_term').removeClass('clearClick').addClass('clickClear');
   $('#newsletter_text').removeClass('clearClick').addClass('clickClear');
   $('input.clickClear').focus(function() {
      startText = $(this).val();
      $(this).val('').addClass('focus');
   });
   $('input.clickClear').blur(function() {
      blurText = $(this).val();
      if (blurText == '') {
         $(this).val(startText).removeClass('focus');
      };
   });

//----------------------------------  set pagination previous and next button urls 

   $('#pagination a:first').addClass('prev').clone().replaceAll('ul#page-nav li#pn-prev a');
   $('#pagination a:last').addClass('next').clone().replaceAll('ul#page-nav li#pn-next a'); 
    
	$("#page #pagination a:first,#page #pagination a:last").remove();
    var pagination = $("#book-page #page").html(); 

    $(".paginatewrap").html(pagination); 
	$("#book-page #page").remove();  
	
    $("#pagination").append($(this).find(".pagination_ellipsis"));
  
	
//----------------------------------  create translation list functionality

	$("#translationlist").hide();
	$("#translation a:first").toggle(function(){
		$(this).addClass("down");
		$("#translationlist").slideDown("fast");
		return false;
	},function(){ 
		$(this).removeClass("down");
		$("#translationlist").slideUp("fast");
		return false;   
	});
	
	$("#languagelist").hide();
	$("#language a:first").toggle(function(){
		$(this).addClass("down");
		$("#languagelist").slideDown("fast");
		return false;
	},function(){ 
		$(this).removeClass("down");
		$("#languagelist").slideUp("fast");
		return false;   
	}); 
	
//----------------------------------  toggles live translation to live in translationlist   

	$("#translationlist a[name='"+$.cookie('translation-ck')+"']").addClass("live");
	$("#selected #trans").text($("#translationlist a.live").text()); 
	
	$("#translationlist a.active").click(function(){ 
		$("#translationlist a.live").removeClass("live");
		$(this).addClass("live"); 
        $.ajax({
            data:"trans="+$(this).attr('name'),
			dataType:"html", 
            url: "/_inc/ajax-set-cookie.php",
            timeout: 1000,
            type:"POST",
            async:false, 
            error: function(){
            },
            success: function(){
             	translation = $.cookie('translation-ck');  
				window.location = onRead();                                        
            }
        });
	});
	
	 
    function onRead(){
		var eurl = window.location.href.replace("http://", "");
	   	var arry = eurl.split("/"); 
		chapter = arry[3]; 
		var loc;
		if(arry[1] == "read"){ 
			if(arry[4]){
				loc = "/read/"+translation+"/"+arry[3]+"/"+arry[4];  
			}else{
			   loc = "/read/"+translation+"/"+arry[3];   
			}
		}else{
			loc = "/read/"+translation+"/chapter-one/";
		} 
		return loc;
	}   
	
//----------------------------------  returns chapter or page type you are on either {if on read will reaturn chapter if on sort will return sort}  

	function getChapter(){
		var eurl = window.location.href.replace("http://", "");
	   	var arry = eurl.split("/");
	 	if(arry[1] =="read"){
		        return arry[3]; 
			}else{
				return  arry[1];
			}
		 
	}
	
//-----------------------------------  sets nav item to current based on current chapter	
	
	var curChap = new Array();
	curChap["chapter-one"] = "chapter1";
	curChap["chapter-two"] = "chapter2";
	curChap["chapter-three"] = "chapter3";
	curChap["chapter-four"] = "chapter4";
	curChap["chapter-five"] = "chapter5";
	curChap["chapter-six"] = "chapter6";
	curChap["chapter-seven"] = "chapter7";
	curChap["chapter-eight"] = "chapter8";
	curChap["chapter-nine"] = "chapter9"; 
	
    var chp = getChapter();  
	$("#nav_chapters li#"+curChap[chp]).addClass("current");
	
//----------------------------------  translation cookie  

	       var translation;
		   var kookie = $.cookie('translation-ck'); 

		   if(kookie){
			   tanslation = kookie;
			}
			
//----------------------------------  loads tag counts 

	   $("#keywords ul li").each(function(){   
			var tagtxt = $(this).find("a").text();  
			var chapter = getChapter();
			//window.console.log(tagtxt + " | " + getChapter + " | " + $.cookie('translation-ck'));
			$(this).find("span").load('/_inc/ajax-tag-count.php',{'tag':tagtxt,'chapter':chapter,'trans':$.cookie('translation-ck')});

		}); 
			
//----------------------------------  toggle utility bar 

		 var utilwidth = $("#footer-utility").width();  
		 $("#footer-utility #close").click(function(){ 
			   $("#footer-nav h3, #quicklinks").addClass("hide");  
			     $("#footer-utility,#quicklinks").animate({
				       left:(-120), opacity: 0
				    }, 100, "linear", function(){
					    $("#openutil").show().animate({ left: 0 },{ duration:100});
				}); 
				$("#footer-nav h3").hide();  
		}); 
		
		$("#openutil").click(function(){ 
				$("#footer-nav h3, #quicklinks").removeClass("hide");  
				$(this).animate({left:-36},{duration:100});
				$("#footer-nav h3").show(); 
				$("#footer-utility, #quicklinks").animate({ left:0, opacity: 1 }, { duration: 100 });
				
				  
		}); 
		
		  $("#openutil").hide().animate({left:-36});
		
		
//----------------------------------  Share with a friend form functionality;
		
	    $("#shareform").hide();
         
         $("#share a").click(function(){ 
			 var url = window.location.href;
			 $("#tellafriend textarea").attr("value","");
             $("#tellafriend textarea").attr("value","Visit this page: "+ url);
             $("#shareform").slideToggle("fast");
         }); 

		$("#shareform .close").click(function(){
			$("#shareform").slideUp("fast"); 
			$("#response").hide().html("");
		});
         
           $("#response").hide();
           $("#tellafriend").validate({
    				rules: {
 					email: {
 						required: true,
 						email: true
 					},
 					toemail: {
 					    required: true,
 						email: true
                     },
 					name:{ 
 					   required:true,
 					   minlength: 2
 					},
 					toname:{ 
 					required:true,
 					minlength: 2
 					}
 				},
 				messages: {
 					email: "Please enter a valid email address",
 					toemail: "Please enter a valid email address",
 					name: "Please enter your name",
 					toname: "Please enter the recievers name"
 									},
 				submitHandler: function(form) { 
	
						//challengeField = $("input#recaptcha_challenge_field").val();
					    //responseField = $("input#recaptcha_response_field").val();
				  
					        	 //$("#captchaStatus").html(" ");
					       
					      		 var inputs = [];
	                             $("#response").html("<p>Sending Form...</p>").show();
	                             $('#tellafriend input').each(function(){
	                                inputs.push(this.name + '=' + escape(this.value));
	                             });

	           					  	$('#tellafriend textarea').each(function(){

	                                  inputs.push(this.name + '=' + escape(this.value));
	                              });
	                             $.ajax({
	                                 data: inputs.join('&'),
									 dataType:"html", 
	                                 url: "/_inc/tellform.php",
	                                 timeout: 3000,

	                                 error: function(){
	                                   $('#response').html("<strong>Err: Email Not Set Try Again Later</strong>");   
	                                 },
	                                 success: function(r){
	                                   $("#response").html(r);
	                                 }
	                             });//end of html send
                             //return false;
 						}
 			        });   


//---------------------------------- Bookmark Article  
             
				$("#bookmark a").click(function(){ 
					var eurl = window.location.href;
					//$.cookie('bookmark',null,{ expires: 7, path: '/', domain: 'matthewhenry.monkcms.net', secure: true });
					$.cookie('bookmark', eurl, { expires: 7, path: '/', domain: 'matthewhenry.org', secure: false }); 
					$(this).fadeOut(100,function(){ $(this).fadeIn(500);});  
				   
					return false;
				});
 			
//---------------------------------- Index Popup
              
 			$("#ql-index a").click(function(){ 
			   		if($("#index-util").length > 0){ 
				            if($("#index-util:hidden")){
					                $("#index-util").fadeIn(300); 
					   				$("#toc-util:visible").fadeOut(300);
							 }
						   
						}else{
							 $("#footer-utility").append("<div id='index-util'><a class='close'>close</a><div id='utilwrap'><div class='top clearfix'><h2>Index</h2> <div class='keytxt'><p>The index page can be used to help direct you to pages in the book which reflect on a particular keyword, topic, or theme.</p></div></div><div class='index-inner'></div></div</div>");
							$("#index-util a.close").click(function(){$(this).parent().fadeOut(300);return false;});   
							 $("#index-util").hide();
							 $("#index-util").fadeIn(500);
							 $("#toc-util:visible").fadeOut(300);
							 $("#footer-utility .index-inner").html("<img src='/_img/ajax-loader.gif' alt='loading'/>");
							 $("#footer-utility .index-inner").load('/tag-index.php',function(){ 
							 	 $('.index-inner').columnize({ columns:3 });
								 $(".index-inner .column h2").each(function(){ $(this).prev("p").addClass("last");});
							     $(".index-inner .column p:last").addClass("last");  
							});
					
							$("#index-util a.close").click(function(){
					                  $("#ql-index a").trigger("toggle");
				   				});
						}
						$("body").click(function(){$("#index-util:visible, #toc-util:visible").fadeOut(300);});
						return false;      
			}); 
			
		   
		
//---------------------------------- Index Popup

		   $("#ql-toc a").click(function(){ 
		   //if($("#index-util:visible")){$("#footer-utility #index-util").fadeOut(300);}
		   if($("#toc-util").length > 0){ 
				if($("#toc-util:hidden")){
				    $("#toc-util").fadeIn(300);
				  	$("#index-util:visible").fadeOut(300);
				}else if($("#toc-util:visible")){
					 $("#toc-util").fadeOut(300); 
				}
			}else{
				 $("#footer-utility").append("<div id='toc-util'><a class='close'>close</a><div class='top clearfix'><h2>Table Of Contents</h2> </div><div class='toc-inner'></div></div>");
				   $("#toc-util a.close").click(function(){$(this).parent().fadeOut(300);return false;});   
				   $("#toc-util").hide();
				   $("#toc-util").fadeIn(500);
				   $("#index-util:visible").fadeOut(300);  
				   $("#footer-utility .toc-inner").html("<img src='/_img/ajax-loader.gif' alt='loading'/>");
				   $("#footer-utility .toc-inner").load('/toc.php');                                     
			} 
			$("body").click(function(){$("#index-util:visible, #toc-util:visible").fadeOut(300);}); 
			return false;  
		});
		
	   
		
		  
		
		
		
	    
		$("#newsletter div:gt(2)").wrapAll("<div class='boxes clearfix'></div>");
        $("#newsletter div:lt(3)").wrapAll("<div class='person-info clearfix'></div>"); 

 		function getUrlVars()
		{
		    var vars = [], hash;
		    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

		    for(var i = 0; i < hashes.length; i++)
		    {
		        hash = hashes[i].split('=');
		        vars.push(hash[0]);
		        vars[hash[0]] = hash[1];
		    }
		    return vars;
		}
		var urlVars = new Array();
		urlVars  = getUrlVars();
		
		if(urlVars["id"] == 1){
			$("#newsletter").before("<div class='response'>Your sign-up was successful. Thank you for your interest.</div>");
			$(".response").hide();
			$(".response").fadeIn("slow");
		}
		
 
				
				
		//delete to add all translations 
		/*$("#translationlist a").each(function(){
	
			 switch($(this).attr("name")){
				case "nas-corporate":
					$(this).hide();
					break;
				case "nas-first-person":
					$(this).hide();
					break;
			}
		}); */
		 if($("#newsletter").length > 0){
    	 $("#newsletter").submit(function(){
              if($("#newsletter input[type=checkbox]").is(":checked")){ 
				  $("#newsletter .error").remove();   
                  return true;
				}
			$("#newsletter .boxes").before("<div class='error'>Please Select A Translation</div>");
			return false;
		 });
		
		$("#newsletter input[type=checkbox]").change(function(){

			 $("#newsletter .error").fadeOut(function(){$(this).remove();});     
		});
	}
    				  	 
 

	//----------------------------------  reftag javascript

});