function bindSubmitButton() { 
  $(".newAccountSubmit").click(function() { 
    $(this).attr("disabled","disabled").after('<div class="newAccountLoader"><img src="/images_08/ajax-loader3.gif" border="0" class="NewAccountLoading" /><div class="newAccountLoaderStatus"> Please wait...</div></div>');
    newSignup();
  });
};
function newSignup() {
       var FirstName = $("#FirstName").val();
       var LastName = $("#LastName").val(); 
       var UserName = $("#UserName").val();
       var Password = $("#Password").val();
       var Email = $("#Email").val();
       var getDataString = 'CreateAccount=true&FirstName='+FirstName+'&LastName='+LastName+'&UserName='+UserName+'&Password='+Password+'&Email='+Email;
       $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/auth/createAccountJSONP.html?'+getDataString+'&format=json&callback=?',
         function(data){
	        if(data.status == 'Activation') {
		        var activationForm = '<BR><BR><fieldset class="activationForm"><legend>Account Activation</legend><span class="activationError"></span>To activate your account, please check your email for an activation code and enter it below.<BR><BR><label style="font-weight:bold;" for="activation">Activation Code</label><BR><input type="text" name="activation" id="activation" class="activationCode"><input type="button" value="Activate" id="activationSend" name="activationSend" class="activationSend"><input type="hidden" name="activationUserName" id="activationUserName" value="'+UserName+'"><input type="hidden" name="activationPassword" id="activationPassword" value="'+Password+'"></fieldset>';
		        $(".NewAccountWrapper").fadeOut("fast", function() { 
				  $(this).html(activationForm).ready(function() { bindActivationForm(); });
				  $(this).css('background-color','#DDE5EE');
			    }).fadeIn("slow");			
           } else if(data.status == 'reSentActivation') { 
				/* TODO */
				$(".newAccountErrors")
				                       .fadeOut("fast")
				                       .html('A new activation code has been sent.')
				                       .fadeIn("slow");
			    $(".newAccountSubmit").removeAttr("disabled");
			    $(".newAccountLoader").remove();
				/* /TODO */			
           } else { 
	              $(".newAccountErrors")
	                                    .fadeOut("fast",function() { 
 				                        $(this).html('<ul class="signupErrorArray">'+data.status+'</ul>');  })
                                       .fadeIn("slow");
				  $(".newAccountSubmit:visible").removeAttr("disabled");
				  $(".newAccountLoader").remove();
           }
       });
};
function bindActivationForm() { 
	  $(".activationSend").click(function() { 
		 $(".activationSend").attr('disabled','disabled');
	     var activationCode = $("#activation").val();
    	 var UserName = $("#activationUserName").val();
    	 var currPassword = $("#activationPassword").val();
	     var getDataString = 'u='+UserName+'&a='+activationCode;
	     $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/auth/activationJSONP.html?'+getDataString+'&format=json&callback=?',
		 function(data) {
   	       if(data.status == "Success") {
  		     $(".commentsShareTray:visible").stop().scrollTo( 0, { axis:'x', speed:1200, easing:'easeOutElastic' } );
             $(".NewAccountWrapper:visible").remove();
	 		 $(".loginUserName").val(UserName);
			 $(".loginPassword").val(currPassword);
             var loginFetcher = 'http://posting.austinchronicle.com/gyrobase/userMacros/auth/login.html?loginUserName='+UserName+'&loginPassword='+currPassword+'&callback=?';
 		     $.getJSON(loginFetcher,function(data) {
		      if(data.status == "Success") {
				var loginUserID = data.UserID;
		     	$.cookie('UserName',data.UserName,{ expires: 1, path: '/', domain: 'austinchronicle.com' });               
				$.cookie('UserID',loginUserID, { expires: 1, path: '/', domain: 'austinchronicle.com' });
    			var $this = $(".chronicleLogin:visible");
    	        authenticate($this);
			    pageTracker._trackEvent('Comments','Logging in',"User: "+data.UserName);
			  } else {
				/* login failed. cookie problem? */
                $(".activationError").html(data.status);
   		        $(".activationSend").removeAttr('disabled');
		  	  }
		    });
		  } else { 
   		    $(".activationError").html(data.status);
  		    $(".activationSend").removeAttr('disabled');
		  } 
		 });	
	  });	 
	};	
function authenticate($this) { 
        $($this).fadeOut("fast");
	    var statusFetcher = 'http://posting.austinchronicle.com/gyrobase/userMacros/auth/getStatus.html?callback=?';
	    $.getJSON(statusFetcher,function(data) {  
	      if(data.status == "Active") { 		  
		    var currUserName = $.cookie('UserName');
			var date = new Date();
	        var timestamp = date.getTime();
		    $('.chronicleLogin').html('<nobr>logged in as: <b>'+currUserName+'</b>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="/gyrobase/Registration/Login?signout=true&cachebuster='+timestamp+'">sign out</a></nobr>').ready(function() { 
				$('.chronicleLogin').fadeIn("fast");
			    $('.fbStatus').fadeOut("fast");
				var sessID = $.cookie('UserID');
				var getFancybox = $("#fancy_wrap:visible").html();
				if(getFancybox != null) { $.fn.fancybox.close(); }
			});
	      } else {
            /* TODO: add error message before fading login-form back in. Most likely cookies are disabled */
            cookiePrompt = 'Sorry, you must have cookies enabled to login';
	    	$($this).fadeIn("fast");
	 	  }	 
	    });
};
	
function forgotPasswordSend() {
  var forgotEmail = $("#forgotPasswordEmail").val();
  var getDataString = 'Email='+forgotEmail+'&callback=?';
  $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/auth/forgotPasswordJSONP.html?'+getDataString,function(data) {
    if(data.status == "Your username and password have been emailed to you.  Make sure your spam filter will allow @austinchronicle.com email addresses.") {
   	  $('.forgotPasswordWrapper').html(data.status);
	  pageTracker._trackEvent('Comments','Forgot Password',"Email: "+forgotEmail);
	} else { $('#forgotError').html(data.status);}
  });
};

function checkMaxLength(obj){
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
  if (obj.getAttribute && obj.value.length>mlength) {
    obj.value=obj.value.substring(0,mlength);
    alert( "Sorry, there is a limit of "+mlength+" characters for comments." );
    obj.focus();
    return false;
  };
  return true;
};

function forgotPassword() { 
 
};
function backToForm(){$(".backComment").click(function(){$('.commentsPreview').slideUp("fast");$(".previewComment:visible").removeAttr("disabled").val('Preview Comment');});};
function toEntity(s) { //convert UTF-8 chars to HTML entities.
	var h='';for(i=0;i<s.length; i++){if(s.charCodeAt(i)>127){h+='&#'+s.charCodeAt(i)+';';}else{h += s.charAt(i);};};return h;
};
function previewPost() { 
  $(".f").submit(function() { return false; });
  $(".previewComment").click(function(e) { 
	var UserName = $.cookie('UserName');
	var UserID = $.cookie('UserID');
	var loginUserName = $(".loginUserName").val();
	var loginPassword = $(".loginPassword").val();
	var Headline = $(".Headline:visible").val();
	var Message = $(".commentMessage:visible").val();
	Message = Message.replace(/\n/g,'<br />');
	//Headline = Headline.replace(';','__SEMI__');
	//Headline = Headline.replace('&','--AMPERSAND--');
	//Headline = Headline.replace('#','--HASH--');
	//Message = Message.replace(';','__SEMI__');
	//Message = Message.replace('&','--AMPERSAND--');
	//Message = Message.replace('#','--HASH--');
	Headline = replaceExtChars(Headline,false);
	Message = replaceExtChars(Message,false);
	Headline=toEntity(Headline);
	Message=toEntity(Message);
	Headline = escape(Headline);
	Message = escape(Message);	
	
	if(!UserName || !UserID) { 
	  var loginFetcher = 'http://posting.austinchronicle.com/gyrobase/userMacros/auth/login.html?loginUserName='+loginUserName+'&loginPassword='+loginPassword+'&callback=?';
 	  $.getJSON(loginFetcher,function(data) {
	     if(data.status == "Success") {
		    var loginUserID = data.UserID;
		    $.cookie('UserName',data.UserName,{ expires: 1, path: '/', domain: 'austinchronicle.com' });               
			$.cookie('UserID',loginUserID, { expires: 1, path: '/', domain: 'austinchronicle.com' });
  		   $.ajax({ type: 'POST',
  	 		   url: "/gyrobase/userMacros/comments/previewComment.html",
  	 		   data: "loginUserName="+loginUserName+"&loginPassword="+loginPassword+"&Headline="+Headline+"&Message="+Message,
  	 		   beforeSend: function (xhr) { 
	 		     $(".previewComment:visible").before('<img src="/images_08/ajax-loader3.gif" border="0" class="previewLoading" style="float:right;" />').attr("disabled","disabled").val('loading...');
  	 		   },
  	 		   success: function(c){
	             $(".previewLoading").remove();
	             $(".commentsPreview").html(c).ready(function() { 
		           $('.commentsPreview').slideDown("fast",function() { 
				     var $this = $(".chronicleLogin:visible");
    	             authenticate($this);
	                 postComment();
	                 backToForm();
					 $(".previewComment:visible").val('Previewing- '+loginUserName); 
 					 pageTracker._trackEvent('Comments','Previewing');
        	       });
	             });
		  	   }
	        });
		} else { 
		alert('Sorry, there was a problem logging you in: ' +data.status);
		}
	  });
	  } else {  
	  /* we already have a cookie. let's give it a shot! */
	  $.ajax({ type: 'POST',
  	 		   url: "/gyrobase/userMacros/comments/previewComment.html",
  	 		   data: "loginUserName="+loginUserName+"&loginPassword="+loginPassword+"&Headline="+Headline+"&Message="+Message,
  	 		   beforeSend: function (xhr) { 
			     $(".previewComment:visible").before('<img src="/images_08/ajax-loader3.gif" border="0" class="previewLoading" style="float:right;" />').attr("disabled","disabled").val('loading...');
  	 		   },
  	 		   success: function(c){
	             $(".previewLoading").remove();
	             $(".commentsPreview").html(c).ready(function() { 
		           $('.commentsPreview').slideDown("fast",function() { 
	                 postComment();
	                 backToForm();
					 $(".previewComment:visible").val('Previewing'); 
        	       });
	             });
		  	   }
	        });
	  }
	  
  });
};
function replaceExtChars(text,output) {
		text = text.replace(eval('/&/g'), '&amp;');
		fromTo = new Array('&AElig;','Æ','&Aacute;','Á','&Acirc;','Â',' &Agrave;','À','&Aring;','Å','&Atilde;','Ã','&Auml; ','Ä','&Ccedil;','Ç','&ETH;','Ð','&Eacute;','É','& Ecirc;','Ê','&Egrave;','È','&Euml;','Ë','&Iacute;' ,'Í','&Icirc;','Î','&Igrave;','Ì','&Iuml;','Ï','&N tilde;','Ñ','&Oacute;','Ó','&Ocirc;','Ô','&Ograve; ','Ò','&Oslash;','Ø','&Otilde;','Õ','&Ouml;','Ö',' &THORN;','Þ','&Uacute;','Ú','&Ucirc;','Û','&Ugrave ;','Ù','&Uuml;','Ü','&Yacute;','Ý','&aacute;','á', '&acirc;','â','&aelig;','æ','&agrave;','à','&aring;','å','&atilde;','ã','&auml;','ä','&brvbar;','¦', '&ccedil;','ç','&cent;','¢','&copy;','©','&deg;',' °','&eacute;','é','&ecirc;','ê','&egrave;','è','&e th;','ð','&euml;','ë','&frac12;','½','&frac14;','¼ ','&frac34;','¾','&gt;','>','&gt','>','&iacute;',' í','&icirc;','î','&iexcl;','¡','&igrave;','ì','&iq uest;','¿','&iuml;','ï','&laquo;','«','&lt;','<',' &lt','<','&mdash;','—','&micro;','µ','&middot;','· ','&ndash;','–','&not;','¬','&ntilde;','ñ','&oacut e;','ó','&ocirc;','ô','&ograve;','ò','&oslash;','ø','&otilde;','õ','&ouml;','ö','&para;', '¶','&plusmn;','±','&pound;','£','&quot;','\"','&r aquo;','»','&reg;','®','&sect;','§','­','-','&sup1 ;','¹','&sup2;','²','&sup3;','³','&szlig;','ß','&t horn;','þ','&tilde;','˜','&trade;','™','&uacute;', 'ú','&ucirc;','û','&ugrave;','ù','&uuml;','ü','&ya cute;','ý','&yen;','¥','&yuml;','ÿ','&rsquo;','\’');
		if (output) { fromTo[fromTo.length] = '&amp;'; fromTo[fromTo.length] = '&'; };
		for (i=0; i < fromTo.length; i=i+2) {
			text = text.replace(eval('/'+fromTo[i+1]+'/g'), fromTo[i]);
			return (text);
		};
};
function postComment() { 
  $(".postComment:visible").click(function(e) { 
	var Headline = $(".Headline:visible").val();
	var Message = $(".commentMessage:visible").val();
	var Postmark = $(".Postmark").attr("checked");
	var PrintStatus = $(".PrintPermission").attr('checked');
    if(PrintStatus == true) {var PrintPerm = $(".PrintPermission").val();} else { var PrintPerm = ''; }
	var Phone = $(".userPhone").val();
	var ContainerID = $("#ContainerID").val();
	var ForumSection = $("#ForumSection").val();
	var loginUserName = $.cookie('UserName');
	Message = Message.replace(/\n/g,'<br />');
	Message = Message.replace('declare','declar\\e;');
	Headline = Headline.replace('declare','declar\\e;');
	//Headline = Headline.replace('declare','declar\\e;');
	//Headline = Headline.replace('#','--HASH--');
	//Headline = Headline.replace('&','--AMPERSAND--');
	//Headline = Headline.replace(';','__SEMI__');
	Message = Message.replace('declare','declar\\e;');
	//Message = Message.replace('#','--HASH--');
	//Message = Message.replace('&','--AMPERSAND--');
	//Message = Message.replace(';','__SEMI__');
	Headline = replaceExtChars(Headline,false);
	Message = replaceExtChars(Message,false);
	Headline=toEntity(Headline);
	Message=toEntity(Message);
	Headline = escape(Headline);
	Message = escape(Message);
	var getDataString = 'Headline='+Headline+'&Message='+Message+'&ContainerID='+ContainerID+'&ForumSection='+ForumSection+'&PrintPermission='+PrintPerm+'&Postmark='+Postmark+'&Phone='+Phone+'&callback=?';
	getDataString = encodeURI(getDataString);
	$('#postComment').val('Sending...').attr('disabled','disabled').before('<img src="/images_08/ajax-loader3.gif" border="0" style="float:right;" />');
    $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/comments/postComment.html?'+getDataString,function(data) {
	  //var myData = data.status.replace(/\n/g,'<br />');
	  //if(window.console) { console.log(myData); }
	  if(data.status.match("success")) {
	     var newCommentID = data.status.replace(/success/,"");
		 $.ajax({ type: 'GET',
  	 		   url: "/gyrobase/userMacros/comments/quickView.html?commentOBJID="+newCommentID,
  	 		   data: "loginUserName="+loginUserName+"&Headline="+Headline+"&Message="+Message,
  	 		   success: function(c){
					$('.commentsPreview').slideUp("fast");
   		            $('#Message').val('');
					$('#Headline').val('');
					$('#Headline').attr('value','');
					$(".commentsOuter").append(c); 
  				    $('#successCommentListener').trigger('click');
					$(".previewComment:visible").removeAttr("disabled").val('Preview Comment'); 
				 	pageTracker._trackEvent('Comments','Posted- '+loginUserName);
		  	   }
	        });
	  } else { 
	      alert('There was a problem completing your request: '+ data.status +' Please correct the problem and try again.');
	  }
	
  	});	
  }); 
};
/* FB */
function mailCommentReplies() { 
  var currentPostID = $("#newCommentID").val();
  var mailType = $('.mailCommentReplies').attr('rel');
  $('.mailCommentReplies').unbind('click').before('<img src="/images_08/ajax-loader3.gif" border="0" style="float:right;" />').attr({src: '/images_08/commonSprites/accept-disabled.gif', alt:'Please wait...',title:'Please Wait...'});
  $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/comments/emailReplies.html?currentPostID='+currentPostID+'&format=json&callback=?',function(data) {  
	if(data.status == "success") {
	  $('#emailCommentsPromptInner').html('<br><br><span style="font-size:13px; margin-top:25px;">All set! Replies to this post will be mailed. <br><a href="javascript:" OnClick="declineCommentReplies();">Close</a> </span>');
	} else {
	  $('#emailCommentsPromptInner').html(data.status);
	}
  });
};
function declineCommentReplies() { $('.promptTagOuter').fadeOut('slow'); $('.promptTagWrapper').fadeOut('slow').remove();  };
function accountError(){$(".fbStatus").html('<span style="font-weight:bold; color:red;">Sorry, we were unable to log you in. Please correct the problem before posting.</span>');};
function shareTray() {$('.shareItem').click(function() { var shareOID = $(this).attr('rel'); var cn = $(this).attr('data-cn'); var service = $(this).attr('data-service'); $.post("macrosFeatured.html", { sOID: shareOID, sCN:cn, sService:service }); pageTracker._trackEvent('Blogs', 'Sharing Item', 'Service:'+service+', oid:'+shareOID);});};

function lookupPhone() { 
   var prVal = $('.userPhone').val();
   if(prVal) {    console.log(prVal+'test'); return true; } 
    var currUserName = $.cookie('UserName');
	if(currUserName != undefined) {   
	   var getDataString = 'u='+currUserName;
       $.getJSON('http://posting.austinchronicle.com/gyrobase/userMacros/auth/checkPhoneJSONP.html?'+getDataString+'&format=json&callback=?',
        function(data){if(data.status == 'found') { return true; } else { return false; };});
	} else {
	  return false;	
	};
};
function phonePrompt() { 
  $('.userPhone').keyup(function(e) { 
  inp = $(this).val();
  if(!isNaN(inp)) {
    $('.phoneError').fadeOut('slow')
    var keylength = inp.length;
    if(keylength > 6) {
      $('.sendPhone').css('color','green').attr('disabled',false);
      $('.sendPhone').click(function() { 
          $(".userPhoneContainer").fadeOut('fast');
	      $(".userPhonePos").fadeOut('fast');
      });
    } else {
      $('.phoneError').fadeOut('slow'); 
  	  $('.sendPhone').css('color','gray').attr('disabled','disabled');	
    };
  } else {  
      if(e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39) {
        $('.phoneError').fadeIn('fast');
	    $('.sendPhone').css('color','gray').attr('disabled','disabled');
      };
  };
  });
  $(".Postmark").click(function() { 
      var  checkStatus = $(this).attr('checked');
	  var numberExists = false;
	 // var numberExists = lookupPhone();
	  if(numberExists == false) {
    	  if(checkStatus == false) { 
	        // $(this).attr('checked',false);
            $(".userPhoneContainer").fadeOut('fast');
	        $(".userPhonePos").fadeOut('fast');
	        // $(".LTEPrompt").show();
	      } else { 
	        //  $(this).attr('checked','checked');
            $(".userPhoneContainer").fadeIn('slow');
	        $(".userPhonePos").fadeIn('slow');
	        // $(".LTEPrompt").hide();
	      };
	  };
      return true;
  });
};

function showSignupBox() { 
		if(window.console) { console.log('1'); }
		/* you can find this in /scripts/jQuery/userMacros/comments/formComments.js */
		$('.NewAccountWrapper').show();
		if(window.console) { console.log('2'); }
		bindSubmitButton();
};
  
$(function() { 
	if(window.console) { console.log('a'); }
    $("#successCommentListener").fancybox({hideOnContentClick:false,overlayShow: true});
if(window.console) { console.log('b'); }
    previewPost();
if(window.console) { console.log('c'); }
	phonePrompt();	
	if(window.console) { console.log('d'); }
	$(".previewComment:visible").removeAttr("disabled");
	if(window.console) { console.log('e'); }
	$('.createAccountLink').click(function() { 
	  $('.NewAccountWrapper').show();
	bindSubmitButton();	
	});
	
	$(".createAccountLink").fancybox({hideOnContentClick:false,frameHeight:420,frameWidth:800,callbackOnShow:showSignupBox });
	$(".authForgotPass").fancybox({hideOnContentClick:false,frameHeight:200,callbackOnShow:function() { 
	   $("#forgotPasswordEmail").focus();
 	   $(".forgotPasswordSubmit").click(function() { forgotPasswordSend(); });
	   $(".forgotWrapper input").keydown(function(e) { var key = e.charCode || e.keyCode || 0; if(key == 13) { forgotPasswordSend(); } });
	}});
	
	$('.accountPerksLink').fancybox();	
	$('.accountLinksFieldset').show('fast');
	$(".extrasContainer").show("fast");
	shareTray();
});

