var GLOBAL_DIR = "";

jQuery(document).ready(function($){
  $('.comment-form').submit(function(){
    submitCommentForm($(this));
    return false;
  });
  
   $('.comment-form-preview').click(function(){
      previewComment($(this));
      return false;
  });

  
  
  //COMMENT WYSIWYG
  
  tinyMCE.init({
  		// Location of TinyMCE script
  		//script_url : '/site/tiny_mce/tiny_mce.js',
  
  		// General options
                mode : "specific_textareas",
                editor_selector : "forum-comment-box",
  		theme : "advanced",
  		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
  
  		// "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontsizeselect,|,link,unlink,anchor,image,|,bullist,numlist,|,code",
  	
  		// Theme options
  		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,forecolor,link,unlink,image",
  		theme_advanced_buttons2 : "",
  		theme_advanced_buttons3 : "",
  		theme_advanced_buttons4 : "",
  		theme_advanced_toolbar_location : "top",
  		theme_advanced_toolbar_align : "left",
  		theme_advanced_statusbar_location : "bottom",
  		theme_advanced_resizing : true,

  		// Example content CSS (should be your site CSS)
  		content_css : "/site/tiny_mce/themes/advanced/editor_content.css",
    
  		height: "300px",
		width: "570px",

		
  		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "js/template_list.js",
                external_link_list_url : "js/link_list.js",
                external_image_list_url : "js/image_list.js",
                media_external_list_url : "js/media_list.js",
  
                force_br_newlines : false,
                force_p_newlines : true,
                
  		// Replace values for the template plugin
  		template_replace_values : {
  		}
	});
  

  // default search box text
  $('#search-form-input')
  .focus(function(srcc){
    if ($(this).val() == $(this)[0].title){
      $(this).addClass("active");
      $(this).val("");
    }
  })
  .blur(function(){
    if ($(this).val() == ""){
      $(this).removeClass("active");
      $(this).val($(this)[0].title);
    }
  });
  $('#search-form-input').blur();

  // Reset Font Size
  var originalFontSize = $('body').css('font-size');

  $(".resetFont").click(function(){
    deleteCookie('fontSize');
    $('body').css('font-size', originalFontSize);
    $('.changeFont')
    .css('background-color', '#fdb815')
    .animate({
      backgroundColor: '#ffffff'
    }, 5000, function() {
      // Animation complete.
    });
  });

  var cookieFontSize = getCookie('fontSize');
  if ( cookieFontSize ) {
    var currentFontSizeNum = parseFloat(cookieFontSize, 10);
    $('body').css('font-size', currentFontSizeNum);
    $('.changeFont')
    .css('background-color', '#fdb815')
    .animate({
      backgroundColor: '#ffffff'
    }, 5000, function() {
      // Animation complete.
    });
  }
  
  // Increase Font Size
  $(".increaseFont").click(function(){
    var currentFontSize = $('body').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $('body').css('font-size', newFontSize);
    $('.changeFont')
    .css('background-color', '#fdb815')
    .animate({
      backgroundColor: '#ffffff'
    }, 5000, function() {
      // Animation complete.
    });
    setCookie('fontSize', newFontSize, 1); // set cookie for 1 day
    return false;
  });
  
  // Decrease Font Size
  $(".decreaseFont").click(function(){
    var currentFontSize = $('body').css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*0.8;
    $('body').css('font-size', newFontSize);
    $('.changeFont')
    .css('background-color', '#fdb815')
    .animate({
      backgroundColor: '#ffffff'
    }, 5000, function() {
      // Animation complete.
    });
    setCookie('fontSize', newFontSize, 1); // set cookie for 1 day
    return false;
  });


  $("#hero").jcarousel({
    auto: 10,
    scroll: 1,
    visible: 1,
    wrap: 'both',
    animation: 1000,
    initCallback: carousel_initCallback,
    itemVisibleInCallback: {
      onAfterAnimation:  carousel_next
    },
    buttonNextHTML: "",
    buttonPrevHTML: ""
  });

  //MegaMenu

  $(".megamenu").megamenu({
    enable_js_shadow:false
  });



  tinyMCE.init({
    // Location of TinyMCE script
    //script_url : '/site/tiny_mce/tiny_mce.js',

    // General options
    mode : "specific_textareas",
    editor_selector : "richtextsimple",
    theme : "advanced",
    plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

    // Theme options
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,forecolor,link,unlink,image",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_buttons4 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    //theme_advanced_statusbar_location : "bottom",
    theme_advanced_resizing : true,
    

    // Example content CSS (should be your site CSS)
    content_css : "/site/tiny_mce/themes/advanced/editor_content.css",

    relative_urls : false,



    file_browser_callback : "tinyBrowser",
    remove_script_host : false,

    height: "300px",
    width: "450px",

    // Drop lists for link/image/media/template dialogs
    template_external_list_url : "js/template_list.js",
    external_link_list_url : "js/link_list.js",
    external_image_list_url : "js/image_list.js",
    media_external_list_url : "js/media_list.js",

    force_br_newlines : false,
    force_p_newlines : true,

    // Replace values for the template plugin
    template_replace_values : {
  }
  });

  $('.autosearchme').each(function(){
    var autosearch = $(this).val();
    $(this).parent().append($("#frontendForm").html());
  });

  // Reset Font Size
  $(".resetFont").click(function(){
    $('.articleContent p, .articleContent caption, .comment-display-message').css('font-size', '13px');
  });
  // Increase Font Size
  $(".increaseFont").click(function(){
    $('.articleContent p, .articleContent caption, .comment-display-message').css('font-size', '15px');
  });
  // Decrease Font Size
  $(".increaseFont2").click(function(){
    $('.articleContent p, .articleContent caption, .comment-display-message').css('font-size', '16px');
  });



});

function dropShadows()
{

}

function hideShadows()
{

}

function previewComment(obj)
{
  	var commentBox = obj.parent().children(".clearfix").children("textarea.comment-form-textbox");
        var objid = commentBox.attr('id');
        //alert(objid);
  	//var comment = commentBox.val();
        var comment =  tinyMCE.get(objid).getContent();
        //alert(comment);
  	
  	$("#comment-preview-area").html(comment);
  	$("#comment-preview-click-link").attr("href", "#TB_inline?height=300&width=570&inlineId=comment-preview-box");
  	tb_init('a.thickbox');
  	$("#comment-preview-click-link").click(); 	
}



/** Comment functions **/
function submitCommentForm(frm)
{
  
  var type = frm.children(":input[name=type]").val();
  var id = frm.children(":input[name=id]").val();
  var withComments = frm.children(":input[name=withComments]").val();
  var reply = frm.children(":input[name=reply]").val();
  var vote = "";
  var follow = "";
  var commentID = "";

  var commentBox = frm.children(".clearfix").children("textarea.comment-form-textbox");
  var comment = "";
  if (type == 'forum')
  {
          var objid = commentBox.attr('id');
          comment =  tinyMCE.get(objid).getContent();
  }
  else
  {
          comment = commentBox.val();
  }
  
  
  
  
  

  if($("input[name=comment-subscribe-checkbox]:checked").val() && reply == 0)
  {
  	follow = 1;
  }

  comment = $.trim(comment);

  if(comment == "")
    return false;

//  if(!(frm.children("div.'comment-check-parent").children(":input[name=comment-check]").is(':checked')))
//  {
//    alert("You must tick the checkbox regarding the Terms of Use to post a comment.");
//    return false
//  }
  if(type == "")
  {
    alert("Your Life Choices system error - Comment form error TYPE_01");
    return false;
  }
  if(id == "")
  {
    alert("Your Life Choices error - Comment form error IDENTIFIER_01");
    return false;
  }

 
 
  if(type != 'forum')
  {
	  /*if(reply != 0)
	  {
	    frm.parent().parent().find(".comment-new:last").append(getCommentScript(comment));
	    $(".comment-form-reply").remove();
	  }
	  else
	  {
	    frm.parent().parent().find(".comment-new:last").append(getCommentScript(comment));
	  }*/
  }
  else
  {
          comment = comment.replace(/\n/g, "");
  }
  //alert(comment);
  //comment = comment.replace(/&nbsp;/g, "<br/>");
  //comment = unescape(comment);
  
  var rtnString = {};
  rtnString["comment"] = comment;
  rtnString["type"] = type;
  rtnString["id"] = id;
  rtnString["vote"] = vote;
  rtnString["follow"] = follow;
  rtnString["reply"] = reply;
  
     $.ajax({
		   type: "POST",
		   url: "/comment/addComment",
		   //data: "comment=" + comment + '&type=' + type + '&id=' + id + '&vote=' + vote + '&follow=' + follow + '&reply=' + reply,
                   data: rtnString,
		   dataType:"xml",
		   success: function(xml){

                      $(xml).find("comment").each(function()
                      {
                          commentID = $(this).find("id").text();
                      });
                      
		      
		      
		       if(type == 'forum')
		       {
                                tinyMCE.get(objid).setContent('');
		       		//alert("about to redirect");
		      		window.location.href = '/the_meeting_place/' + id + '#comment-' + commentID;
		      		location.reload();
		      		//alert('/the_meeting_place/' + id + '#comment-' + commentID);
		      		return;
		       }
                       else
                       {
                               window.location.href = document.URL + '#comment-' + commentID;
                               location.reload();
                               commentBox.val("");
                       }
		      
		      $('.comment-new .comment-display-new:last').attr('id','comment-' + commentID);
		      
		      var js = "commentRemove(" + commentID + ", false);return false";
		      var newclick = new Function(js);

		      $('#comment-' + commentID + ' .comment-display-delete a').click(newclick);
		      
		      //if(reply == 0)
		      	//$('.comment-new:last .comment-display-replay a').attr('onclick',"commentReply(" + commentID + ", " + id + ", '" + type + "');return false");
		      	
		   }
	});
		 

  // fade new comment to white
  $('#comment-' + commentID)
  .animate({
    backgroundColor: '#ffffff'
  }, 10000, function() {
    // Animation complete.
  });
  
  
  return false;
}


function getCommentScript(comment)
{
  var rtnText = '<div class="comment-display-new"><div class="comment-display-message"><div class="comment-display-avatar">';
  rtnText += '<span class="comment-display-name">You</span><Br /><span class="comment-display-time">Just now</span>';
  
  rtnText += '<div class="comment-display-delete"><a href="#">remove</a></div>';
  //rtnText += '<div class="comment-display-reply"><a onclick=""); return false;" href="#">reply</a></div>';
  
  rtnText += '</div>';
    
  rtnText += '';
  rtnText += comment;
  rtnText += '</div><div class="clearAll"></div></div>';
  return rtnText;
}

function commentRemove(id, isSub)
{
  if(!confirm("Are you sure you want to remove this comment?"))
  {
    return;
  }
  $("#comment-" + id).css("background-color", "#F2BFBF");
  $("#comment-" + id + " .comment-display-delete").html("removing...");
  $.post(GLOBAL_DIR + "/comment/removeComment", {
    id : id
  }, function(xml){
    $("#comment-" + id).fadeTo("slow", 0.33);
    $("#comment-" + id + " .comment-display-delete").html("comment removed");
  });
}


function commentReport(id, isSub)
{
  if(!confirm("Are you sure you want to report this comment?"))
  {
    return;
  }
  $("#comment-" + id).css("background-color", "#F2BFBF");
  $("#comment-" + id + " .comment-display-delete").append("reporting...");
  $.post(GLOBAL_DIR + "/comment/reportComment", {
    id : id
  }, function(xml){
    $("#comment-" + id).fadeTo("slow", 0.33);
    $("#comment-" + id + " .comment-display-delete").html("comment reporting");
  });
}

function commentReply(id, id2, type)
{
  var rntText = '<form name="comment-form" class="comment-form-reply comment-form" onSubmit="return false"><div class="clearfix"><textarea class="comment-form-textbox comment-form-reply-box" name="comment" style="width: 500px"></textarea></div><input type="hidden" name="type" value="' + type + '"><input type="hidden" name="withComments" value="0"><input type="hidden" name="reply" value="' + id + '"><input type="hidden" name="id" value="'+ id2 + '">' ;
  
  //rntText += "<div style='float: left' class='comment-check-parent'><input type='checkbox' class='comment-check' name='comment-check'></div><div style='float: left; width: 400px; padding-left: 5px; margin-bottom: 5px'>I understand that submission of this comment is covered by the <a href='http://www.yourlifechoices.com.au/about/terms-of-use' target='_blank'>Terms of Use</a> by which I am bound.</div>" ;
  
  rntText += '<div class="clearAll"></div>';
  
  if(type == 'forum')
  	 rntText += '<input type="button" class="comment-form-preview" value="Preview Post"  style="font-size: 12px"  />';
  
  rntText += '<input type="submit" class="comment-form-submit" value="Post Reply" style="font-size: 12px"  /></form>';
  
  $("#comment-" + id + " .comment-display-extra").html(rntText);
  $('.comment-form-reply').submit(function(){
    submitCommentForm($(this));
    return false;
  });
  
  if(type == 'forum')
  {
  	doCommentReplyWYSIWYG();
  }
}

function commentEdit(id, id2, type)
{
        $("#comment-edit-box").html('');
        var comment = $("#comment-" + id + " .comment-display-message .comment-display-content").html();
        //alert(comment);
        var rntText = '<h3>Edit your comment</h3> ';
        rntText += '<form name="comment-form" class="comment-form-reply comment-form" action="/comment/editComment" method="post">';
        rntText += '    <input type="hidden" name="type" value="' + type + '"/>';
        rntText += '    <input type="hidden" name="reply" value="' + id + '"/>';
        rntText += '    <input type="hidden" name="id" value="' + id2 + '"/>        ';
        rntText += '    <div id="comment-edit-area">';
        rntText += '        <textarea id ="comment-edit-textbox" class="comment-form-reply-box" name="comment" style="width: 500px">' + comment + '</textarea>';
        rntText += '    </div>';

        rntText += '    <input type="submit" class="comment-form-submit" value="Update Comment"/>';
        rntText += '    <input type="button" class="comment-form-preview-close" value="Cancel" onClick="tb_remove();" />';
        rntText += '</form>';
    
        $("#comment-edit-box").html(rntText);

  	$("#comment-edit-click-link").attr("href", "#TB_inline?height=300&width=570&inlineId=comment-edit-box");
  	tb_init('a.thickbox');
  	$("#comment-edit-click-link").click(); 	
        
        if(type == 'forum')
        {
            doCommentReplyWYSIWYG();
        }
}


function validateThread(vv)
{
  if(vv.name.value == "")
  {
    alert("Please provide a name for this thread.");

  }
  if(vv.description.value == "")
  {
    alert("Please provide a description for this thread.");
  }
  return true;
}


function doPop(url)
{
  var newwindow=window.open(url,'previewpain','height=500,width=800,scrollbars=yes,resizable=yes');
  if (window.focus)
  {
    newwindow.focus()
  }

}

function setCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function deleteCookie(name) {
  setCookie(name,"",-1);
}


function doCommentReplyWYSIWYG()
  {
  	
  	 tinyMCE.init({
	  		// Location of TinyMCE script
	  		//script_url : '/site/tiny_mce/tiny_mce.js',
	  
	  		// General options
                        mode : "specific_textareas",
                        editor_selector : "comment-form-reply-box",
                        
	  		theme : "advanced",
	  		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
	  
	  		// "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontsizeselect,|,link,unlink,anchor,image,|,bullist,numlist,|,code",
	  	
	  		// Theme options
	  		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,forecolor,link,unlink,image",
	  		theme_advanced_buttons2 : "",
	  		theme_advanced_buttons3 : "",
	  		theme_advanced_buttons4 : "",
	  		theme_advanced_toolbar_location : "top",
	  		theme_advanced_toolbar_align : "left",
	  		theme_advanced_statusbar_location : "bottom",
	  		theme_advanced_resizing : true,
	  
	  		// Example content CSS (should be your site CSS)
          		content_css : "/site/tiny_mce/themes/advanced/editor_content.css",
	    
	  		height: "200px",
			width: "520px",

	  		// Drop lists for link/image/media/template dialogs
                        template_external_list_url : "js/template_list.js",
                        external_link_list_url : "js/link_list.js",
                        external_image_list_url : "js/image_list.js",
                        media_external_list_url : "js/media_list.js",
	  
                        force_br_newlines : false,
                        force_p_newlines : true,
                        
	  		// Replace values for the template plugin
	  		template_replace_values : {
	  		}
                        
	});
	
	   $('.comment-form-preview').click(function(){
	      previewComment($(this));
	      return false;
  	});
  }
