(function($) {
	$(document).ready(function() {
		var basePath = Drupal.settings.basePath;
		var modPath = basePath + "r_tbc_fixer/";
		$book = $("#fix-tbc-form #edit-book");
		$chapter = $("#fix-tbc-form #edit-chapter");
		$example = $("#fix-tbc-form #edit-example");
		$caption = $("#fix-tbc-form #edit-caption");
		$code = $("#fix-tbc-form #edit-code");
		$caption_form = $("#r-fixer-caption-form");
		$code_form = $("#r-fixer-code-form");
		$updating = $("#fix-tbc-page #updating");
		$done = $("#fix-tbc-page #done");
		$example.attr("multiple", "enabled");


		function reset() {
			for (var i = 0, l = arguments.length; i < l; i++) {
				switch (arguments[i]) {
					case "book":
						$book.html("<option value='0'>Please select a book</option>");
						break;
					case "chapter":
						$chapter.html("<option value='0'>Please select a chapter</option>");
						break;
					case "example":
						$example.html("<option value='0'>Please select a example</option>");
						break;
					case "caption":
						$caption.val("");
						break;
				}
			}
		}
		$(".select-book").hide();
		$(".select-chapter").hide();
		$(".enter-chapter-name").hide();
		$(".chapter-example-chk").hide();
		$(".select-example").hide();
		$(".enter-caption").hide();
		$(".example-code-edit").hide();
		$(".well").hide();
		$(".update-button").hide();
		$book.change(function() {
			reset("chapter", "example", "caption");
			var book_id = $(this).val();
			if (book_id < 1) {
				$(".select-chapter").hide();
				$(".select-example").hide();
				$(".enter-caption").hide();
				$(".enter-chapter-name").hide();
				$(".chapter-example-chk").hide();
				$(".example-code-edit").hide();
				$(".well").hide();
				$(".update-button").hide();
			} else {
				$(".select-chapter").show();
				$(".select-example").hide();
				$(".enter-chapter-name").hide();
				$(".chapter-example-chk").hide();
				$(".enter-caption").hide();
				$(".example-code-edit").hide();
				$(".well").hide();
				$(".update-button").hide();
			}
			$.ajax({
				url: modPath + "ajax/book/" + book_id,
				type: "POST",
				dataType: "html",
				success: function(data) {
					$chapter.html(data);
				}
			});
		});
		$chapter.change(function() {
			reset("example", "caption");
			var chapter_name = $('option:selected', this).attr("data-chaptername");
			var chapter_id = $(this).val();
			if (chapter_id < 1) {
				$(".select-example").hide();
				$(".enter-caption").hide();
				$(".enter-chapter-name").hide();
				$(".chapter-example-chk").hide();
				$(".example-code-edit").hide();
				$(".well").hide();
				$(".update-button").hide();
			} else {
				$(".select-example").show();
				$(".enter-chapter-name").show();
				$(".chapter-example-chk").show();
				$("#edit-chapter-name").val(chapter_name);
				$(".enter-caption").hide();
				$(".example-code-edit").hide();
				$(".update-button").show();
			}
			$.ajax({
				url: modPath + "ajax/chapter/" + chapter_id,
				type: "POST",
				dataType: "html",
				success: function(data) {
					$example.html(data);
					$example.attr("size", $("#fix-tbc-form #edit-example option").length);
				}
			});
		});
		$example.change(function() {
			reset("caption");
			var example_id = $(this).val();
			var example_name = $('option:selected', this).attr("data-exampleid");
			var example_caption = $(this).text();
			if (example_id < 1) {
				$(".enter-caption").hide();
				// $("#edit-caption").val("");
				$(".example-code-edit").hide();
				$(".well").hide();
				$(".update-button").hide();
			} else {

				$(".enter-caption").show();
				$("#edit-caption").val(example_name);
				$(".example-code-edit").show();
				$(".well").show();
				$(".update-button").show();
			}
			$.ajax({
				url: modPath + "ajax/example/" + example_id,
				type: "POST",
				dataType: "html",
				success: function(data) {
					var code = $(data).filter("#code").text();
					/* checking whether it is for .well or textarea */
					if ($code.hasClass("fix-caption-code")) {
						$code.text(code);
					} else {
						$code.val(code);
					}
					var caption = $(data).filter("#caption").html();
					try {
						$caption.val(caption);
					} catch (e) {
						return;
					}
				}
			});
		});
		//edit caption form submit
		$caption_form.submit(function(e) {
			var example_id = $example.val();
			var chapter_id = $('option:selected', $chapter).attr("data-chapterid");
			if ($('.chapter-caption-chk').prop('checked') == true && $(
					'.example-caption-chk').prop('checked') == true) {
				if (example_id != "0" && chapter_id != "0") {
					var caption = $caption.val();
					caption = caption.trim();
					caption = caption.replace(/\s\s+/g, ' ');
					if(validateCaption(caption) == true) {
						alert('Enter valid text for example caption');
						return false;
					}
					var chapter_caption = $("#edit-chapter-name").val();
					chapter_caption = chapter_caption.trim();
					chapter_caption = chapter_caption.replace(/\s\s+/g, ' ');
					if(validateCaption(chapter_caption) == true) {
						alert('Enter valid text for chapter caption');
						return false;
					}
					if (caption == '' || chapter_caption =='') {
						alert('Please enter new caption ');
						return false;
					}
					$updating.show();
					$.ajax({
						url: modPath + "ajax/update-both/" + example_id,
						type: "POST",
						data: {
							example_id: example_id,
							caption: caption,
							chapter_id: chapter_id,
							chapter_caption: chapter_caption
						},
						dataType: "html",
						success: function(data) {
							$chapter.trigger("change");
							$book.trigger("change");
							$updating.hide();
							$done.show();
							$done.fadeOut("slow");
						}
					});
				} else {
					alert("No entry is selected.")
				}
			} else if ($('.example-caption-chk').prop('checked') == true) {
				if (example_id != "0") {
					var caption = $caption.val();
					caption = caption.trim();
					caption = caption.replace(/\s\s+/g, ' ');
					if(validateCaption(caption) == true) {
						alert('Enter valid text');
						return false;
					}
					if (caption == '') {
						alert('Please enter new caption ');
						return false;
					}
					$updating.show();
					$.ajax({
						url: modPath + "ajax/update-example/" + example_id,
						type: "POST",
						data: {
							example_id: example_id,
							caption: caption,
						},
						dataType: "html",
						success: function(data) {
							$chapter.trigger("change");
							$updating.hide();
							$done.show();
							$done.fadeOut("slow");
						}
					});
				} else {
					alert("No example selected.")
				}
			} else if ($('.chapter-caption-chk').prop('checked') == true) {
					if (chapter_id != "0") {
					var chapter_caption = $("#edit-chapter-name").val();
					alert(chapter_caption);
					chapter_caption = chapter_caption.trim();
					chapter_caption = chapter_caption.replace(/\s\s+/g, ' ');
					if(validateCaption(chapter_caption) == true) {
						alert('Enter valid text for chapter caption');
						return false;
					}
					if (chapter_caption == '') {
						alert('Please enter new caption ');
						return false;
					}
					$updating.show();
					$.ajax({
						url: modPath + "ajax/update-chapter/" + example_id,
						type: "POST",
						data: {
							chapter_id: chapter_id,
							chapter_caption: chapter_caption
						},
						dataType: "html",
						success: function(data) {
							$chapter.trigger("change");
							$book.trigger("change");
							$updating.hide();
							$done.show();
							$done.fadeOut("slow");
						}
					});
				} else {
					alert("No example selected.")
				}
			} else {
				alert("Please select the checkbox option")
			}
			e.preventDefault();
		});
		$code_form.submit(function(e) {
			var example_id = $example.val();
			if (example_id != "0") {
				var code = $code.val();
				code = code.trim();
				if (code == '') {
					alert('Please enter new code');
					return false;
				}
				$.ajax({
					url: modPath + "ajax/code/" + example_id,
					type: "POST",
					data: {
						code: code
					},
					dataType: "html",
					success: function(data) {
						$chapter.trigger("change");
						$updating.hide();
						$done.show();
						$done.fadeOut("slow");
						$(".example-code-edit").show();
					}
				});
			} else {
				alert("No example selected.")
			}
			e.preventDefault();
		});

		function validateCaption(text){
			var re = /([a-zA-Z|*|_|.|+|-|\\|?|/|!|~|!|@|#|$|%|^|&|(|)|<|>|{|}|;|:|\"|\'|,])\1{2,}/;
			return re.test(text);
		}
		/* toggle in edition */
		$ind_ed = $(".ind-ed");
		$ind_ed.click(function(e) {
			var aicte_id = $(this).attr("data-aicte");
			$t = $(this);
			$.ajax({
				url: modPath + "ajax/ind-ed/" + aicte_id,
				type: "GET",
				dataType: "html",
				success: function(data) {
					$tr = $t.parents("tr:first");
					if ($tr.hasClass("orange")) {
						$t.parents("tr:first").removeClass("orange");
						$t.html("Mark");
					} else {
						$t.parents("tr:first").addClass("orange");
						$t.html("Unmark");
					}
				},
			});
			e.preventDefault();
		});
	});
})(jQuery);
;/*})'"*/;/*})'"*/
(function($) {
	$(document).ready(function() {
		var basePath = Drupal.settings.basePath;
		//var modPath = basePath + "textbook_companion_fixer/";
		var modPath = basePath +
			"r_tbc_fixer/ajax/edit-book-category/";
		$category_form = $("#fix-tbc-category-form");
		$(".main-subcategory-table-div").hide();

		/*********************************************/
		//$('#main-subcategory-table-'+ 1).show();
		//var main_cat_chk_value = [];
		$("input[name='ids[]']:checked").each(function() {
			main_cat_chk_value = $(this).val();
			console.log('ooo' + main_cat_chk_value);
			if (main_cat_chk_value) {
				$('#main-subcategory-table-div-id-' + main_cat_chk_value).show();
			} else {
				$('#main-subcategory-table-div-id-' + main_cat_chk_value).hide();
			}
		});

		$('.main-category-checkbox').change(function() {
			main_cat_chk_value = $(this).val();
			if (!this.checked)
				$('#main-subcategory-table-div-id-' + main_cat_chk_value).hide();
			else
				$('#main-subcategory-table-div-id-' + main_cat_chk_value).show();
		});

		$("#fix-tbc-category-form").on('click', '#btn-add', function() {
			//$('#btn-add').click(function(){
			var selectID = $(this).attr("data-cid");
			console.log(selectID);
			$('#subcats-' + selectID + ' option:selected').each(function() {
				$('#selected-subcats-' + selectID).append("<option value='" + $(this)
					.val() + "'>" + $(this).text() + "</option>");

				/**********************/
				var pref_id = $('.prefrence_id').val();
				var main_cat_chk_value = selectID;
				var sub_cat_select_value = $(this).val();
				$.ajax({
					url: modPath,
					type: "POST",
					data: {
						pref_id: pref_id,
						main_category: main_cat_chk_value,
						sub_category: sub_cat_select_value,
						action: "add"
					},
					dataType: "html",
					success: function(data) {
						//alert("Updated");
						console.log("My data:" + data);
						$updating.hide();
						$done.show();
						console.log("data1: " + main_cat_chk_value + " data2: " +
							sub_cat_select_value + " data3: " + pref_id);
						$done.fadeOut("slow");
						//alert("ok");
					}
				});
				/**********************/

				$(this).remove();
			});
		});
		$("#fix-tbc-category-form").on('click', '#btn-remove', function() {
			//$('#btn-remove').click(function(){
			var selectID = $(this).attr("data-cid");
			$('#selected-subcats-' + selectID + ' option:selected').each(function() {
				$('#subcats-' + selectID).append("<option value='" + $(this).val() +
					"'>" + $(this).text() + "</option>");
				var action = "delete";
				/**********************/
				var pref_id = $('.prefrence_id').val();
				var main_cat_chk_value = selectID;
				var sub_cat_select_value = $(this).val();
				$.ajax({
					url: modPath,
					type: "POST",
					data: {
						pref_id: pref_id,
						main_category: main_cat_chk_value,
						sub_category: sub_cat_select_value,
						action: action
					},
					dataType: "html",
					success: function(data) {
						//alert("Updated");
						console.log("My data:" + data);
						$updating.hide();
						$done.show();
						console.log(action + "data1: " + main_cat_chk_value +
							" data2: " + sub_cat_select_value + " data3: " + pref_id);
						$done.fadeOut("slow");
						//alert("ok");
					}
				});
				/**********************/
				$(this).remove();
			});
		});

		//$("#main_cat_checkbox").change(function() {
		$("#fix-tbc-category-form").on('change', '.main-category-checkbox',
			function() {
				var selectID = $(this).val();
				prop = $(this).prop('checked');
				if (prop) {
					$('main-subcategory-table-' + selectID).show();
				} else {
					if (confirm('Are you sure?')) {
						alert('Thanks for confirming');
						var action = "delete-main-with-ub-category";
						var pref_id = $('.prefrence_id').val();
						var main_cat_chk_value = selectID;
						console.log(action + "data1: " + main_cat_chk_value + " data2: " +
							action + " data3: " + pref_id);
						//ConfirmFunction();
						$.ajax({
							url: modPath,
							type: "POST",
							data: {
								pref_id: pref_id,
								main_category: main_cat_chk_value,
								sub_category: '',
								action: action
							},
							dataType: "html",
							success: function(data) {
								//alert("Updated");
								location.reload();
								$('main-subcategory-table-' + selectID).hide();
								console.log("My data:" + data);
								$updating.hide();
								$done.show();
								console.log(action + "data1: " + main_cat_chk_value + " data2: " +
									action + " data3: " + pref_id);
								$done.fadeOut("slow");
								//alert("ok");
							}
						});
					} else {
						alert('You have not confirmed the action');
						location.reload();
					}
				}
			});
		/**********************************************************************/
	});
})(jQuery);

function ConfirmFunction() {
	confirm("Are you sure?");
}
;/*})'"*/;/*})'"*/
function getSelectionText(divID) {
	var selectedText = "";
	if (window.getSelection) {
		var sel = window.getSelection();
		var div = document.getElementById(divID);
		if (sel.rangeCount) {
			// Get the selected range
			var range = sel.getRangeAt(0);
			// Check that the selection is wholly contained within the div text
			// if (range.commonAncestorContainer == div.firstChild) {
			var selectedText = range.toString();
			// }
		}
	}
	return selectedText;
}


(function($) {
	$(document).ready(function() {
		$(".fix-caption-code").mousedown(function() {
			$("#edit-caption").val("");
		});
		$(".fix-caption-code").mouseup(function() {
			quotedText = getSelectionText("#fix-caption-code");
			$("#edit-caption").val(quotedText);
		});
		$("#edit-example").mousedown(function() {
			$("#edit-caption").val("");
		});
		$("#edit-example").mouseup(function() {
			quotedText =  $('option:selected', this).attr("data-exampleid");
			$("#edit-caption").val(quotedText);
		});
	});
})(jQuery);
;/*})'"*/;/*})'"*/
(function ($) {

Drupal.behaviors.tableSelect = {
  attach: function (context, settings) {
    // Select the inner-most table in case of nested tables.
    $('th.select-all', context).closest('table').once('table-select', Drupal.tableSelect);
  }
};

Drupal.tableSelect = function () {
  // Do not add a "Select all" checkbox if there are no rows with checkboxes in the table
  if ($('td input:checkbox', this).length == 0) {
    return;
  }

  // Keep track of the table, which checkbox is checked and alias the settings.
  var table = this, checkboxes, lastChecked;
  var strings = { 'selectAll': Drupal.t('Select all rows in this table'), 'selectNone': Drupal.t('Deselect all rows in this table') };
  var updateSelectAll = function (state) {
    // Update table's select-all checkbox (and sticky header's if available).
    $(table).prev('table.sticky-header').andSelf().find('th.select-all input:checkbox').each(function() {
      $(this).attr('title', state ? strings.selectNone : strings.selectAll);
      this.checked = state;
    });
  };

  // Find all <th> with class select-all, and insert the check all checkbox.
  $('th.select-all', table).prepend($('<input type="checkbox" class="form-checkbox" />').attr('title', strings.selectAll)).click(function (event) {
    if ($(event.target).is('input:checkbox')) {
      // Loop through all checkboxes and set their state to the select all checkbox' state.
      checkboxes.each(function () {
        this.checked = event.target.checked;
        // Either add or remove the selected class based on the state of the check all checkbox.
        $(this).closest('tr').toggleClass('selected', this.checked);
      });
      // Update the title and the state of the check all box.
      updateSelectAll(event.target.checked);
    }
  });

  // For each of the checkboxes within the table that are not disabled.
  checkboxes = $('td input:checkbox:enabled', table).click(function (e) {
    // Either add or remove the selected class based on the state of the check all checkbox.
    $(this).closest('tr').toggleClass('selected', this.checked);

    // If this is a shift click, we need to highlight everything in the range.
    // Also make sure that we are actually checking checkboxes over a range and
    // that a checkbox has been checked or unchecked before.
    if (e.shiftKey && lastChecked && lastChecked != e.target) {
      // We use the checkbox's parent TR to do our range searching.
      Drupal.tableSelectRange($(e.target).closest('tr')[0], $(lastChecked).closest('tr')[0], e.target.checked);
    }

    // If all checkboxes are checked, make sure the select-all one is checked too, otherwise keep unchecked.
    updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length));

    // Keep track of the last checked checkbox.
    lastChecked = e.target;
  });

  // If all checkboxes are checked on page load, make sure the select-all one
  // is checked too, otherwise keep unchecked.
  updateSelectAll((checkboxes.length == $(checkboxes).filter(':checked').length));
};

Drupal.tableSelectRange = function (from, to, state) {
  // We determine the looping mode based on the order of from and to.
  var mode = from.rowIndex > to.rowIndex ? 'previousSibling' : 'nextSibling';

  // Traverse through the sibling nodes.
  for (var i = from[mode]; i; i = i[mode]) {
    // Make sure that we're only dealing with elements.
    if (i.nodeType != 1) {
      continue;
    }

    // Either add or remove the selected class based on the state of the target checkbox.
    $(i).toggleClass('selected', state);
    $('input:checkbox', i).each(function () {
      this.checked = state;
    });

    if (to.nodeType) {
      // If we are at the end of the range, stop.
      if (i == to) {
        break;
      }
    }
    // A faster alternative to doing $(i).filter(to).length.
    else if ($.filter(to, [i]).r.length) {
      break;
    }
  }
};

})(jQuery);
;/*})'"*/;/*})'"*/
(function ($) {

/**
 * Attaches sticky table headers.
 */
Drupal.behaviors.tableHeader = {
  attach: function (context, settings) {
    if (!$.support.positionFixed) {
      return;
    }

    $('table.sticky-enabled', context).once('tableheader', function () {
      $(this).data("drupal-tableheader", new Drupal.tableHeader(this));
    });
  }
};

/**
 * Constructor for the tableHeader object. Provides sticky table headers.
 *
 * @param table
 *   DOM object for the table to add a sticky header to.
 */
Drupal.tableHeader = function (table) {
  var self = this;

  this.originalTable = $(table);
  this.originalHeader = $(table).children('thead');
  this.originalHeaderCells = this.originalHeader.find('> tr > th');
  this.displayWeight = null;

  // React to columns change to avoid making checks in the scroll callback.
  this.originalTable.bind('columnschange', function (e, display) {
    // This will force header size to be calculated on scroll.
    self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display);
    self.displayWeight = display;
  });

  // Clone the table header so it inherits original jQuery properties. Hide
  // the table to avoid a flash of the header clone upon page load.
  this.stickyTable = $('<table class="sticky-header"/>')
    .insertBefore(this.originalTable)
    .css({ position: 'fixed', top: '0px' });
  this.stickyHeader = this.originalHeader.clone(true)
    .hide()
    .appendTo(this.stickyTable);
  this.stickyHeaderCells = this.stickyHeader.find('> tr > th');

  this.originalTable.addClass('sticky-table');
  $(window)
    .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
    .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
    // Make sure the anchor being scrolled into view is not hidden beneath the
    // sticky table header. Adjust the scrollTop if it does.
    .bind('drupalDisplaceAnchor.drupal-tableheader', function () {
      window.scrollBy(0, -self.stickyTable.outerHeight());
    })
    // Make sure the element being focused is not hidden beneath the sticky
    // table header. Adjust the scrollTop if it does.
    .bind('drupalDisplaceFocus.drupal-tableheader', function (event) {
      if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) {
        window.scrollBy(0, -self.stickyTable.outerHeight());
      }
    })
    .triggerHandler('resize.drupal-tableheader');

  // We hid the header to avoid it showing up erroneously on page load;
  // we need to unhide it now so that it will show up when expected.
  this.stickyHeader.show();
};

/**
 * Call the header offset function to prevent use of eval().
 *
 * @param accessor
 *   The callback function name.
 * @return
 *   The callback result.
 */
Drupal.tableHeader.callHeaderOffsetFunction = function(accessor) {
  accessor = accessor.split('.');
  var callback = window;
  for (var i = 0, len = accessor.length - 1; i < len; i++) {
    if (typeof callback[accessor[i]] !== 'function' && typeof callback[accessor[i]] != 'object') {
      return 0;
    }
    callback = callback[accessor[i]];
  }
  if (typeof callback[accessor[accessor.length - 1]] === 'function') {
    return callback[accessor[accessor.length - 1]]();
  }
  return 0;
};

/**
 * Event handler: recalculates position of the sticky table header.
 *
 * @param event
 *   Event being triggered.
 */
Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) {
  var self = this;
  var calculateWidth = event.data && event.data.calculateWidth;

  // Reset top position of sticky table headers to the current top offset.
  this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? Drupal.tableHeader.callHeaderOffsetFunction(Drupal.settings.tableHeaderOffset) : 0;
  this.stickyTable.css('top', this.stickyOffsetTop + 'px');

  // Save positioning data.
  var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  if (calculateWidth || this.viewHeight !== viewHeight) {
    this.viewHeight = viewHeight;
    this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop;
    this.hPosition = this.originalTable.offset().left;
    this.vLength = this.originalTable[0].clientHeight - 100;
    calculateWidth = true;
  }

  // Track horizontal positioning relative to the viewport and set visibility.
  var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
  var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition;
  this.stickyVisible = vOffset > 0 && vOffset < this.vLength;
  this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' });

  // Only perform expensive calculations if the sticky header is actually
  // visible or when forced.
  if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) {
    this.widthCalculated = true;
    var $that = null;
    var $stickyCell = null;
    var display = null;
    var cellWidth = null;
    // Resize header and its cell widths.
    // Only apply width to visible table cells. This prevents the header from
    // displaying incorrectly when the sticky header is no longer visible.
    for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) {
      $that = $(this.originalHeaderCells[i]);
      $stickyCell = this.stickyHeaderCells.eq($that.index());
      display = $that.css('display');
      if (display !== 'none') {
        cellWidth = $that.css('width');
        // Exception for IE7.
        if (cellWidth === 'auto') {
          cellWidth = $that[0].clientWidth + 'px';
        }
        $stickyCell.css({'width': cellWidth, 'display': display});
      }
      else {
        $stickyCell.css('display', 'none');
      }
    }
    this.stickyTable.css('width', this.originalTable.outerWidth());
  }
};

})(jQuery);
;/*})'"*/;/*})'"*/
