var ms = new MemberServices();
var mgs = new MessageServices();
var memberId = document.cookie;
var contentId =sGlobalContentID;
var siteId = 1; 
var index = memberId.search(/MemberId=/gi);
var isAjaxLoggedIn = false;

//Gets the encrypted memberId from the cookie
if(index != -1){
memberId = memberId.substr(index+9, memberId.length);
index = memberId.search(/;/gi);
if(index != -1)
  memberId = memberId.substr(0, index);
isAjaxLoggedIn = true;
}
else{
//you're not logged in!!!!!
isAjaxLoggedIn = false;
}


//////////////////////////////////
// Global Async Initializer
//////////////////////////////////
function AsyncInit(AsyncType)
{
	if(AsyncType=="Blog")
	{
	  //Initialize Blog List
	  if(isAjaxLoggedIn)
	  {     
	     UpdateBlogMessage("Retrieving blog list...");                      
	     //Get blog list and load select box
	     getBlogLists();   
		 
		 document.BlogForm.blogtitle.value=sGlobalContentTitle;
	  }
	  else
	  {
	     UpdateBlogMessage("You must be logged in to use the Blog feature");
	     HideDiv("BlogSectionForm"); //hide form              
	  }

	}
}
//////////////////////////////////
// Blog Methods
//////////////////////////////////

//Blog it 
function BlogIt(objBtn)
{
	//Check login state one more time
	if(isAjaxLoggedIn)
	{
	 //HideDiv("BlogSectionForm"); //hide form  

	 UpdateBlogButton("Blogging..", false)
	 
	 var frmBlogForm = document.BlogForm; 
	 var sBlogTitle = frmBlogForm.blogtitle.value;
	 var sBlogText = frmBlogForm.blogtext.value;
	 var sBlogId = frmBlogForm.BlogList.options[frmBlogForm.BlogList.selectedIndex].value;
	 var sMessage = sBlogText + " ("  + sGlobalContentUrl +")";	 
	
	 if(sBlogTitle=="" ||
	 	sBlogText=="")
		{
			alert("You are missing some data, please check your form and try again.")
			UpdateBlogButton("Blog it!", true)
			return;
		}
	
	 ms.postBlogCommments(sBlogId,sBlogTitle,sMessage, postBlogCallback);

	}
}
//Callback for the posting blog WebMethod
function postBlogCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}
	try{
	  var responseNode = xmlDoc.documentElement;

	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
		 HideDiv("BlogSectionForm")   
	     UpdateBlogMessage("Could not post to your blog, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to try again");
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService,
	     //call another function to update the UI, it's up to you        
		 UpdateButtonState("Blog it!", true, "BlogItButton")
		 HideDiv("BlogSectionForm")   
	     UpdateBlogMessage("Blog was sent successfully, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to go back");
	 

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	  alert(e)
	  
	  UpdateButtonState("Blog it!", true, "BlogItButton")
	  HideDiv("BlogSectionForm")  
	  UpdateBlogMessage("Could not post to your blog, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to try again");
	}
}
function TurnBlogFormOn()
{
	UpdateButtonState('Blog it!', true, 'BlogItButton')
}
//Callback for the getBlogLists WebMethod
function getBlogListsCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}

	try{
	  var responseNode = xmlDoc.documentElement;
	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
	    UpdateBlogMessage("Could not retrieve your blog information, please try again later");
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService,
	     //call another function to update the UI, it's up to you                   
	    UpdateBlogList (responseNode);

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	}
}
//Calls the AJAX function for getting the user's blog list
function getBlogLists(){
	ms.retrieveBlogList(siteId, memberId, getBlogListsCallback);
} 
//Update blog list
function UpdateBlogList(xmlElement){

	var elements;
	var selectBlogList;
	var divBlogSectionForm;
	var blogId;
	var blogName;               

	divBlogSectionForm = document.getElementById("BlogSectionForm")
	selectBlogList = document.getElementById("BlogList");
	elements = xmlElement.getElementsByTagName("Blog");             

	if(elements.length > 0){      
	  ShowDiv("BlogSectionForm");//show form
	  HideDiv("BlogSectionMessage");//hide message
	  for(i=0;i<=elements.length;i++)
	  {
	      blogId = elements[i].getAttribute("BlogId");
	      blogName = elements[i].getAttribute("BlogName");                      
	      selectBlogList.options[i] = new Option(blogName,blogId);
	  }

	}
	else
	{
	  UpdateBlogMessage("You have not set up any blogs.  <a href='http://my.break.com/Member/Profile/MyProfile.aspx'>Click Here</a> to add your blog information");
	}
} 
function UpdateBlogButton(strValue,bIsEnabled)
{
	var objBtn = document.getElementById("BlogItButton")
	objBtn.value = strValue;
	objBtn.disabled = (bIsEnabled)?false:true;
}
function UpdateBlogMessage(strMessage)
{
	var divBlogSectionMessage = document.getElementById("BlogSectionMessage");
	ShowDiv("BlogSectionMessage");
	divBlogSectionMessage.innerHTML = strMessage;
}  

//////////////////////////////////
// Send To Friend Methods
//////////////////////////////////

var oSendToFriendTable = document.getElementById("SendToFriendTable")

//Process form fields and perform quick validation
function processQuickEmailFieldsAndSendEmail()
{
	var sName = document.getElementById("TellAFriend_SenderName");
	var sEmail = document.getElementById("TellAFriend_SenderEmail");
	var sFriends = document.getElementById("TellAFriend_RecipientEmail1");
	var sComments = document.getElementById("TellAFriend_QuickNoteToFriend");
	
    sFriends.value = sFriends.value.replace(/\s/g, "");
	//Do quick validation
	if(sName.value=="" ||
	   sEmail.value=="" ||
	   sFriends.value=="" ||
	   sComments.value=="")
	{
	  alert("Your are missing something in your form.")
	  return;
	}

	//Do a quick email validation
	if(!emailCheck(sEmail.value))
	{
	  alert("Your email is invalid")
	  return;
	}

	//Do a quick email validation for the friends
	var aEmails = sFriends.value.split(',');
	if(aEmails.length>0)
	{
	  for(i=0;i<aEmails.length;i++)
	  {
	    if(!emailCheck(aEmails[i]))
	    {
	      alert("Your friend(s) email is invalid: " + aEmails[i])
	      return;
	      break;                      
	    }
	  }
	}
	UpdateButtonState("Sending...", false, "SendToFriendButton")
	mgs.TellToFriendEmail(sName.value, sEmail.value, sFriends.value, sComments.value, sGlobalContentID, "sendToFriendCallback");
	
	//clearing out the form 
	sName.value = "";
	sEmail.value = "";
	sFriends.value = "";
	sComments.value = "";
}

//Callback for the sendToFriend WebMethod
//Callback for the sendToFriend WebMethod
function sendToFriendCallback(jsonData)
{
    if(jsonData.Response.Code < 0) 
    {
        //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message");
		 
    }
    else
    {
        //All is good, parse the xml if you need the data returned from the WebService
	     //call another function to update the UI, it's up to you    
		 UpdateButtonState("Send It", true, "SendToFriendButton")
		 
    }

}

//////////////////////////////////
// Add to Favorite Methods
//////////////////////////////////   

var divAddToFavoritesMessage = document.getElementById("AddToFavoritesMessage")

//Callback for the addToFavorites WebMethod
function addToFavoritesCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}

	try{
	  var responseNode = xmlDoc.documentElement;
	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
	     if(divAddToFavoritesMessage!=null)
		 {		
		 	if(responseNode.getAttribute("Code")==-3)
			{				
				divAddToFavoritesMessage.innerHTML = "This content is already in your Favorites.";	
				return;
			}
		 
		 	if(responseNode.getAttribute("Message")!= "")
			{
				divAddToFavoritesMessage.innerHTML = responseNode.getAttribute("Message");				
			}
			else
			{	
				divAddToFavoritesMessage.innerHTML = "This content has been added to your Favorites.";		
			}
		 }
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService
	     //call another function to update the UI, it's up to you
	     if(divAddToFavoritesMessage!=null)
		 {
		 	if(responseNode.getAttribute("Message")!= "")
			{
				divAddToFavoritesMessage.innerHTML = responseNode.getAttribute("Message");				
			}
			else
			{				
				divAddToFavoritesMessage.innerHTML = "This content has been added to your Favorites.";
			}			
		 }

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	}
}    
//Calls the AJAX function for adding content to your favorites
function addToFavorites(){
	ms.saveToFavorites(1, memberId, sGlobalContentID, addToFavoritesCallback);
} 