// Sitewide Admin scripts using jquery
$(document).ready(function() {
//jquery Datepicker
	Date.firstDayOfWeek = 7; //show sunday through saturday
	Date.format = 'mm/dd/yyyy'; //show desired date format
	$('.form_date').datePicker({startDate:'01/01/1996'});
	//validate date using validate_date.js
	$(".form_date").blur(function() {
		checkdate(this);
	});
	
//jquery tablesorter
    $(".tablesorter").tablesorter({widgets: ['zebra']});
	$(".tablesorter tbody tr").hover(function() {$(this).addClass("over");}, function() {$(this).removeClass("over");});

//drag and drop table rows sorter
  $(".tablesorter tbody").sortable({
    handle: ".drag_handle",
    axis: "y",
    helper: function(e, tr) {
      var $originals = tr.children();
      var $helper = tr.clone();
      $helper.children().each(function(index) {
        // Set helper cell sizes to match the original sizes
        $(this).width($originals.eq(index).width())
      });
      return $helper;
    },
    update: function(event, ui) {
      var serial = $(this).sortable('serialize');
      $.post("admin_ajax.php?type=sort", serial, function() {
        $(".tablesorter").trigger("update").trigger("applyWidgets", {widgets: ["zebra"]});
      });
    }
  });
	
//checkbox toggle
	$(".checkbox").live("click", function() {
		var name = $(this).attr("name"); //get name
		var checkval = ""; //default the value to nothing
		if ($(this).is(':checked')) {
			checkval = 1;
		}
		$.post("admin_ajax.php", {type: "checkbox", name: name, value: checkval});
	});

//update text box on keyup
	var delayed;
	$(".text_ajax").live("keyup", function() {
		clearTimeout(delayed);
		var value = $(this).val();
		var name = $(this).attr("name"); //get name attribute
		
		if (value) {
			delayed = setTimeout(function() {
				$.post("admin_ajax.php", {type: "text", name: name, value: value});
			}, 600);
		}
	});

//update select on change with ajax
	$(".select_ajax").change(function() {
		var name = $(this).attr("name"); //get name attribute
		var value = $(this).val();
		//make ajax call
		$.post("admin_ajax.php", {type: "text", name: name, value: value});
	});	

//folder select for fileupload
	$("#folder_select").change(function() {
		$(this).parent("form").submit();
	});

//reload folders for fileupload
	$("#reload").click(function() {
		location.reload(true);
		return false;
	});

//upload window for fileupload
	$('#upload_window a').click(function() {
		window.open(this.href,'Upload','width=550,height=200,scrollbars=1,resizable=1,status=0,toolbar=0');
		return false;
	});
	
//show upload graphic
	$("#upload").submit(function() {
		$("#progress").show();
	});

//refresh file admin page when upload is complete
	if ($("div").hasClass(".uploaded")) {
		window.opener.location.reload(true);
	}

//Confirm Delete
	$(".delete_item").click(function() {
		var answer = confirm('Are you sure you want to delete?');
		return answer // answer is a boolean
	});
	
//add tooltip to files to show preview
	$("a.preview").filetip();

//password recovery display
	$("#recover_pw").click(function() {
		$("#recover_box").toggle();
		return false;
	});

//multifile plugin
	$(".multifile").multifile();
	
//WYSIWYG Rich Text Editor using HtmlBox
	if ($("textarea").hasClass("form_rte")) {
		$(".form_rte").htmlbox()
			// Bold, Italic, Underline
			.separator("dots").button("bold").button("italic").button("underline")	
			// Left, Right, Center, Justify
			.separator("dots").button("left").button("center").button("right").button("justify")
			// Ordered List, Unordered List, Indent, Outdent
			.separator("dots").button("ol").button("ul").button("indent").button("outdent")
			// Hyperlink, Image
			.separator("dots").button("hyperlink").button("unlink").button("image")
			// Undo, Redo
			.separator("dots").button("undo").button("redo")
			// HTML code view
			.separator("dots").button("code")
			.init();
	}
	
//limit text length
	$("#meta_keywords, #meta_description").keyup(function() {
		var limit = $(this).val();
		if (limit.length > 250) {
			var maxtext = limit.slice(0, 250);
			$(this).val(maxtext);
		}
	});
	
	
//form fixes and styles
  $('input[type="checkbox"]').css("border", "none");
  $('input[type="submit"], button, .buttonify').button();
	
//add single file
  $(".file-manager").filemanager({"single": true, "title": "Add File"});
//file manager sorter
  $(".files-manager").filemanager({"title": "Add Files"});
  $(".files-sort-active").zebra();
//add single photo
  $(".photo-manager").filemanager({"type": "photo", "single": true, "title": "Add Photo"});
//Photo Sort Gallery
  $(".photos-manager").filemanager({"type": "photo", "title": "Add Photos"});
	
//uploadify multifile uploader
	$("#upload_controls_container").hide();
	$("#upload_window a").each(function() {
		var folder = $(this).attr("href");
		var text = $(this).text();
		var token = $(this).attr("title");
		var id = "#" + $(this).attr("id");
		
		$(this).uploadify({
			"uploader"  		: "swf/uploadify.swf",
			"script"    		: "admin_fileupload_file.php",
			"cancelImg" 		: "images/cancel.png",
			"fileDataName"	: "uploaded_file",
			"multi"     		: true,
			"buttonText"		: text,
			"queueID"				: "upload_queue",
      //"sizeLimit"   	: 8000000,
			"scriptData"		: {"id": folder, "token": token},
			onComplete			: function(evt, queueID, fileObj, response, data) {
         $("#upload_response").prepend(response + "<br/>");
				 $("#upload_controls").hide();
      },
			onSelectOnce		: function(evt, data) {
        $("#upload_response").empty();
				// uploadify controls
				$("#upload_controls_container, #upload_controls").show();
				$("a#upload_start").click(function() {
					$(id).uploadifyUpload();
          return false;
				});
				$("a#upload_clear").click(function() {
					$(id).uploadifyClearQueue();
          $("#upload_controls_container").hide();
          return false;
				});
      }
		});
	});

  function inline_upload() {
    $(".upload_window a").each(function() {
      var $this = $(this);
      var $file_manager = $this.parent().parent();
      var folder = $this.attr("href");
      var text = $this.text();
      var token = $this.attr("title");
      var type = "file";
      var image = "images/btn_file-upload.gif";
      //find out if this is a file or photo
      if ($file_manager.hasClass("photo-manager")) {
        type = "photo";
        image = "images/btn_photo-upload.gif";
      }

      $(this).uploadify({
        "uploader"  		: "swf/uploadify.swf",
        "script"    		: "admin_fileupload_file.php",
        "cancelImg" 		: "images/cancel.png",
        "fileDataName"	: "uploaded_file",
        "auto"       		: true,
        "buttonText"		: text,
        "rollover"      : true,
        "buttonImg"     : image,
        "height"        : 31,
        "width"         : 106,
        //"sizeLimit"   	: 8000000,
        "scriptData"		: {"id": folder, "token": token, "inline": true},
        onComplete			: function(evt, queueID, fileObj, response, data) {
          //make sure an error wasn't present. Else show the image and remove button
					if (response.match(/<div class='error'>/gi)) {
						$file_manager.find(".inline-uploaded").html(response);
					} else {
						var callback = jQuery.parseJSON(response);
						log(callback.length);
	
						if (callback.status != "success") {
							$file_manager.find(".inline-uploaded").html(response);
						} else {
							$file_manager.find("input").val(callback.filename);
							if (type == "photo") {
								$file_manager.find(".inline-uploaded").html('<img src="' + callback.folder + '/tn/' + callback.filename + '" />');
							} else {
								$file_manager.find(".inline-uploaded").html('<a href="' + callback.folder + '/' + callback.filename + '" target="_blank">' + callback.filename + '</a>');
							}
							$file_manager.find(".upload_window").hide();
							$file_manager.find(".remove-file").show();
						}
					}
        }
      });
    });
  }
  inline_upload();
	
	
});
