﻿function contains(arr, value, ignoreCase) {
   var found = false;
   for (var i = 0; i < arr.length; i++) {
      if (ignoreCase) {
         if (arr[i].trim().toUpperCase() == value.toUpperCase()) {
            found = true;
            break;
         }
      }
      else {
         if (arr[i].trim() == value) {
            found = true;
            break;
         }
      }
   }
   return found;
}

//
// todo: Need to wire up an event handler for when searches changes so that searches.filter() can run automatically
//

var searches = {
   categoryLabel: "",
   parentCategoryLabel: "",
   categoryText: "",
   parentCategoryText: "",
   categoryId: "",
   parentCategoryId: "",
   subCategory: "",
   keyword: "",
   format: "",
   permaLink: "",
   redirect: function (type) {
      if (type == "search" && searches.keyword != "") {
         location.href = "/Programs.aspx?search=" + searches.keyword;
         return false;
      }
   },
   filter: function () {
      if (searches.categoryId != "") {
         $(".box").hide();
         $(".box." + searches.categoryId).show();
      }

      if (searches.categoryId != "") {
         $(".introColumn h1").html($("#" + searches.categoryId).html());
         $("p#parentCategoryDescription").html($("#" + searches.categoryId).siblings("span").html());
      }
      else if (searches.parentCategoryId != "") {
         $(".introColumn h1").html($("#" + searches.parentCategoryId).html());
         $("p#parentCategoryDescription").html($("#" + searches.parentCategoryId).siblings("span").html());
      }

      if (searches.keyword != "") {
         $(".introColumn h1").html("Search Results");
         $("p#parentCategoryDescription").html("Your search returned " + (($(".box:visible").length != NaN) ? $(".box:visible").length.toString() : "0") + " results");
         $("#search_input").val(searches.keyword);
      }
   }
}

// This class implements the admin editor for page level content
var contentEditor = {
   dialogBox: null,
   textArea: null,
   editElement: null,
   editorInstance: null,
   edit: function (ev) {
      this.editElement = $(ev.currentTarget);
      contentEditor.textArea = contentEditor.dialogBox.find("textarea");
      contentEditor.textArea.val(this.editElement.html());
      var title = $(this.editElement.find("h1"));
      contentEditor.dialogBox.parent().find(".ui-dialog-title").html((title.html().length != 0) ? title.html() : "&nbsp;");
      contentEditor.dialogBox.dialog("open");

      // we are using the cleditor plugin - config'd here if not already done so earlier in the session
      if (contentEditor.editorInstance == null) {
         this.editorInstance = this.textArea.cleditor({
            width: 526, // width not including margins, borders or padding
            height: 385, // height not including margins, borders or padding
            controls:     // controls to add to the toolbar
                        "bold italic underline strikethrough subscript superscript | font size " +
                        "style | color highlight removeformat | bullets numbering | outdent " +
                        "indent | alignleft center alignright justify | undo redo | " +
                        "rule image link unlink | cut copy paste pastetext | print html |",
            colors:       // colors in the color popup
                        "FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " +
                        "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " +
                        "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " +
                        "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " +
                        "666 900 C60 C93 990 090 399 33F 60C 939 " +
                        "333 600 930 963 660 060 366 009 339 636 " +
                        "000 300 630 633 330 030 033 006 309 303",
            fonts:        // font names in the font popup
                        "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," +
                        "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana",
            sizes:        // sizes in the font size popup
                        "1,2,3,4,5,6,7",
            styles:       // styles in the style popup
                        [["Paragraph", "<p>"], ["Header 1", "<h1>"]],
            useCSS: false, // use CSS to style HTML when possible (not supported in ie)
            docType:      // Document type contained within the editor
                        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
            docCSSFile:   // CSS file used to style the document contained within the editor.
                        "",
            bodyStyle:    // style to assign to document body contained within the editor
                        "margin:4px; font:10pt Arial,Verdana; cursor:text"
         });
      }
      else {
         this.editorInstance[0].updateFrame();
         this.editorInstance[0].refresh();
      }
      
   },

   save: function (callback) {
      $.jmsajax({
         type: "POST",
         url: "/Services/Pages.asmx",
         method: "SetPageContent",
         dataType: "msjson",
         data: {
            url: location.pathname.toLowerCase(),
            elementId: contentEditor.editElement[0].id,
            content: contentEditor.textArea.val()
         },
         error: function (XMLHttpRequest, textStatus, errorThrown) {

         },
         success: function (data, textStatus, XMLHttpRequest) {
            contentEditor.editElement.html(contentEditor.textArea.val());
            // Check to see if we've passed in a contentEditor.close()?
            if (callback) {
               setTimeout(callback, 1);
            }
         }
      });
   },

   close: function () {
      this.editorInstance[0].clear();
      this.dialogBox.dialog("close");
   }
}


$(document).ready(function () {
   // Setup the dialog box to handle admin edits of page level content
   contentEditor.dialogBox = $("#contentEditor").dialog({
      autoOpen: false,
      height: 500,
      width: 550,
      modal: true,
      resizable: false,
      buttons: {
         "Apply": function () {
            contentEditor.save();
         },
         "Cancel": function () {
            contentEditor.close();
         },
         "Ok": function () {
            contentEditor.save('contentEditor.close()');
         }
      }, // buttons

      open: function () {
      },
      close: function () {
      }
   });




   $(".adminEditable").click(function (ev) {
      contentEditor.edit(ev);
   });

//      return;

//      ev.stopPropagation();
//      var $this = $(ev.currentTarget);
//      original = $this;

//      var k = $("<textarea id='currentEditor'></textarea>");
//      $this.after(k).hide();
//      k.html(original.html());
//      k.height(original.height());
//      k.width(original.width());
//      currentEditor = k.cleditor({

//         width: original.width(), // width not including margins, borders or padding
//         height: original.height(), // height not including margins, borders or padding
//         controls:     // controls to add to the toolbar
//                        "bold italic underline strikethrough subscript superscript | font size " +
//                        "style | color highlight removeformat | bullets numbering | outdent " +
//                        "indent | alignleft center alignright justify | undo redo | " +
//                        "rule image link unlink | cut copy paste pastetext | print html | save exit",
//         colors:       // colors in the color popup
//                        "FFF FCC FC9 FF9 FFC 9F9 9FF CFF CCF FCF " +
//                        "CCC F66 F96 FF6 FF3 6F9 3FF 6FF 99F F9F " +
//                        "BBB F00 F90 FC6 FF0 3F3 6CC 3CF 66C C6C " +
//                        "999 C00 F60 FC3 FC0 3C0 0CC 36F 63F C3C " +
//                        "666 900 C60 C93 990 090 399 33F 60C 939 " +
//                        "333 600 930 963 660 060 366 009 339 636 " +
//                        "000 300 630 633 330 030 033 006 309 303",
//         fonts:        // font names in the font popup
//                        "Arial,Arial Black,Comic Sans MS,Courier New,Narrow,Garamond," +
//                        "Georgia,Impact,Sans Serif,Serif,Tahoma,Trebuchet MS,Verdana",
//         sizes:        // sizes in the font size popup
//                        "1,2,3,4,5,6,7",
//         styles:       // styles in the style popup
//                        [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
//                        ["Header 3", "<h3>"], ["Header 4", "<h4>"], ["Header 5", "<h5>"],
//                        ["Header 6", "<h6>"]],
//         useCSS: false, // use CSS to style HTML when possible (not supported in ie)
//         docType:      // Document type contained within the editor
//                        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
//         docCSSFile:   // CSS file used to style the document contained within the editor.
//                        "",
//         bodyStyle:    // style to assign to document body contained within the editor
//                        "margin:4px; font:10pt Arial,Verdana; cursor:text"

//      });

//      // Move our new buttons a smidgen - js coz we don't want to futz with the plugin's css for 2 items
//      $(".cleditorButton[title='Save Changes']").css({ "backgroundRepeat": "no-repeat", "margin": "3px 3px" });
//      $(".cleditorButton[title='Exit Editor']").css({ "backgroundRepeat": "no-repeat", "margin": "3px 3px" });

//      currentEditor.url = location.pathname.toLowerCase();
//      currentEditor.elementId = original[0].id
//      currentEditor.original = original;
//   });






   var search = location.search.substring(1, location.search.length).toLowerCase().split("&");

   for (var i = 0; i < search.length; i++) {
      var subSearch = search[i].split("=");
      switch (subSearch[0].toLowerCase()) {
         case "category":
            var paths = subSearch[1].split("/");
            searches.parentCategoryId = paths[0];
            searches.categoryId = (paths[1] != null) ? paths[1] : "";

            break;
         case "search":
            searches.keyword = (subSearch[1] != null) ? subSearch[1] : "";
            break;

         case "format":
            searches.format = subSearch[1];
            break;
         case "permalink":
            searches.permaLink = subSearch[1];
            break;
      }

   }


   searches.filter();

   //wireup search events
   $("#search_input").keypress(function (event) {
      if (event.keyCode == '13') {
         event.preventDefault();
         searches.keyword = $("#search_input")[0].value;
         searches.redirect("search");
      }
   });

   $("#textsearch").click(function (event) {

      searches.keyword = $("#search_input")[0].value;
      searches.redirect("search");
   });

   $("#search_input").click(function (ev) {
      $(this).val("");
   });






   $(".mainNavItem>a").css("textTransform", "uppercase")

   $(".mainNavItem").mouseover(function () {
      // If there is only one child we don't show it and let the parent click show all
      if ($(this).find("li").length > 1) {
         $(this).find("div").show();
      }
   })

   $(".mainNavItem").mouseout(function () {
      $(this).find("div").hide();
   })

   // Fix some anomolies - move this to the CSS sheet later
   $(".programsNav ul li").css({ float: "none", marginTop: "5px" })

   // Primary and Secondary navigational click event handler
   $(".mainNavItem").click(function (ev) {
      var $ev = $(ev.target);

      var newCategoryId = $ev[0].id;

      if ($ev.parent(".mainNavItem").length == 1) {
         if (newCategoryId != searches.categoryId) {
            searches.parentCategoryId = newCategoryId;
            location.href = "/Programs.aspx?category=" + searches.parentCategoryId + "/";
            return false;
         }
      }
      else if ($ev.parents(".mainNavItem").length == 1) {
         // Category Level Two Click so start by finding it's Level 1 parent
         var newParentCategoryId = $ev.parents(".mainNavItem").find("a")[0].id;

         newCategoryId = $ev[0].id;

         if (searches.parentCategoryId != newParentCategoryId) {
            searches.parentCategoryId = newParentCategoryId;
            searches.categoryId = newCategoryId;

            location.href = "/Programs.aspx?category=" + searches.parentCategoryId + "/" + searches.categoryId.replace(".", "/");
            return false;
         }
         else {
            searches.categoryId = newCategoryId;

         }
      }




      searches.filter();
      return false;
   });



});




