﻿var UIUtilities = {
  BrowserIsIE6: ($.browser.msie && $.browser.version < 7.0),
  BrowserIsIE7: ($.browser.msie && $.browser.version >= 7.0 && $.browser.version < 8.0),
  Shadow: {
    BlurRadius: 20,
    Offset: 3,
    Opacity: 0.2
  },
  
  createImageWaitFunction: function(image, callback) {
    var waitFunction = function() {
      if (!image.complete) {
        setTimeout(waitFunction, 200);
        return;
      }
      
      callback(image);
    };
    
    return waitFunction;
  },
  
  fixImages: function(query) {
    if (UIUtilities.BrowserIsIE6 != true)
      return;
    var queryType = typeof(query);
    if (queryType != "string" && queryType != "function")
      return;
    
    // Stop attempting to process images after two minutes
    var now = new Date();
    var stopProcessingTime = now.getTime() + 120000;
    
    var loops = 0;
    var waitFunction = function() {
      loops++;
      
      // Stop processing if two minutes have elapsed since we began
      var now = new Date();
      if (now.getTime() > stopProcessingTime)
        return;
      
      // Load images based on query
      var images;
      if (queryType == "string")
        images = $(query);
      else if (queryType == "function")
        images = query();
      
      if (images.length <= 0)
        return;
      
      // Check through the array of images and process the ones that have loaded
      var i = 0;
      var unprocessedCount = 0;
      while (i < images.length) {
        var image = images[i];
        if (image.complete) {
          // This image is ready; process it
          image = $(image);
          
          // Determine the image's width, height, etc.
          var width = image.width();
          var height = image.height();
          var src = image.attr("src");
          var title = image.attr("alt");
          var className = image.attr("class");
		  
		  if (className == "ie6PngFix" && width == "" && height == "") {
				width = 70;
				height = 85;
		  }
		  
		  if (className == "ie6PngFix pushAngledRight" && width == "" && height == "") {
				width = 70;
				height = 85;
		  }
          
          if (width != null && height != null && src != null) {
            // Replace the image element with a div that uses Microsoft's
            // AlphaImageLoader to present the graphic
            var replacement = $("<div></div>").css({
//              borderBottom: "solid green 1px",
              width: width,
              height: height,
              cursor: "pointer",
              filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='crop')"
            });
            if (title != null)
              replacement.attr("title", title);
            if (className != null)
              replacement.attr("class", className);
			  
			if (className == "ie6PngFix") {
				replacement.attr("width", width);
				replacement.attr("height", height);
			}
            
            image.replaceWith(replacement);
			//image.remove();
			//image.append(replacement);
			//image.attr('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='crop')");
          } else {
            unprocessedCount++;
          }
        } else {
          unprocessedCount++;
        }
        
        i++;
      }
      
      // If there are still images that haven't loaded yet,
      // wait for a bit and try again
      if (unprocessedCount > 0)
        setTimeout(waitFunction, 500);
//      else
//        $("body").prepend("<h1>Loops: " + loops + "</h1>");
    };
    waitFunction();
  },
  
  createShadowDiv: function(width, height) {
    var shadowWidth = parseInt(width) + (UIUtilities.Shadow.BlurRadius * 2);
    var shadowHeight = parseInt(height) + (UIUtilities.Shadow.BlurRadius * 2);
    
    var shadow = $(document.createElement("div")).addClass("shadow");
    shadow.css({
      width: shadowWidth,
      height: shadowHeight
    });
    
    // Add a backdrop for the shadow PNGs - 32 bit PNGs do not render transparency
    // correctly when an opacity filter is applied to them in *all* versions of IE unless
    // they are composited over an element that has a background color set.  Note that
    // this is a different issue than the issue of displaying transparent PNGs in IE6.
    // TK - this actually is still problematic in IE6; it just doesn't mix the alpha correctly.
//      _this.shadow.append($("<div></div>").css({
//        width: shadowWidth,
//        height: shadowHeight,
//        backgroundColor: "white",
//        opacity: 0.006
//      }));
    
    // Add the actual shadow components on top of the backdrop
    shadow.append($("<div class='top-left'></div>"));
    shadow.append($("<div class='top-right'></div>"));
    shadow.append($("<div class='bottom-left'></div>"));
    shadow.append($("<div class='bottom-right'></div>"));
    shadow.append($("<div class='center-left'></div>").css({
      top: 50,
      left: 0,
      height: shadowHeight - (50 * 2)
    }));
    shadow.append($("<div class='center-top'></div>").css({
      top: 0,
      left: 50,
      width: shadowWidth - (50 * 2)
    }));
    shadow.append($("<div class='center-right'></div>").css({
      top: 50,
      right: 0,
      height: shadowHeight - (50 * 2)
    }));
    shadow.append($("<div class='center-bottom'></div>").css({
      bottom: 0,
      left: 50,
      width: shadowWidth - (50 * 2)
    }));
    
//    shadow.css({opacity: UIUtilities.Shadow.Opacity});
    
    return shadow;
  }
};

var CookieUtilities = {
  createCookie: function(name, value, days, path) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = "; expires=" + date.toGMTString();
    } else {
      expires = "";
    }
    
    document.cookie = name + "=" + value + expires + "; path=" + (path == null ? "/" : path);
  },
  
  readCookie: function(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;
  }
};

// A Hashtable-like object for allowing us to store multiple name/value pairs
// of data in a single cookie - this spares us having to have a unique cookie for
// each page that requires one, and sidesteps the bugginess of IE's support for
// path-based document.cookie entries (which would be the preferred method of
// handling this)
NameValuePairCookie.prototype = new Object();
NameValuePairCookie.prototype.constructor = NameValuePairCookie;

NameValuePairCookie.prototype.setValue = function(name, value) {
  if (this.items == null)
    this.items = new Array();
  
  // Try to find this item in the array
  for (var i=0; i<this.items.length; i++) {
    if (this.items[i].name == name) {
      // Found it - update the value (might be nice to remove the pair from
      // the array if the value is null...)
      this.items[i].value = value;
      return;
    }
  }
  
  // Item was not found in the array - append it
  this.items.push({
    name: name,
    value: value
  });
};

NameValuePairCookie.prototype.getValue = function(name) {
  if (this.items == null)
    return null;
  
  // Try to find this item in the array
  for (var i=0; i<this.items.length; i++) {
    if (this.items[i].name == name) {
      // Found it
      return this.items[i].value;
    }
  }
  
  // Item was not found in the array
  return null;
};

NameValuePairCookie.prototype.save = function(days) {
  var cookieValue = "";
  
  if (this.items != null) {
    for (var i=0; i<this.items.length; i++) {
      if (cookieValue.length > 0)
        cookieValue += ",";
      
      cookieValue += encodeURIComponent(this.items[i].name) + ":" + encodeURIComponent(this.items[i].value);
    }
  }
  
  CookieUtilities.createCookie(this.name, cookieValue, days);
};

function NameValuePairCookie(name) {
  this.name = name;
  this.rawValue = CookieUtilities.readCookie(this.name);
  this.items = new Array();
  
  if (this.rawValue == null)
    return;
  
  // Pairs are represented by "NAME:VALUE,"
  var pairs = this.rawValue.split(',');
  for (var i=0; i<pairs.length; i++) {
    var pair = pairs[i].split(':');
    if (pair.length != 2)
      continue;
    
    this.items.push({
      name: decodeURIComponent(pair[0]),
      value: decodeURIComponent(pair[1])
    });
  }
}

// A generic container for cross-faded paginated content
PageContainer.prototype = new Object();
PageContainer.prototype.constructor = PageContainer;

PageContainer.prototype.swap = function(duration) {
  if (this.page == null || this.buffer == null)
    return;
  
  if (typeof(duration) != "number" || duration <= 0) {
    this.page.css({
      opacity: 0,
      display: "none",
      position: "absolute"
    });
    
    this.buffer.css({
      opacity: 1,
      display: "block",
      position: "relative",
      filter: ""
    });
  } else {
    var _this = this;
    this.container.css("height", this.container.height());
    
    // Measure the page & buffer
    this.page.stop();
    this.page.css({
      display: "block",
      position: "absolute"
    });
    var pageHeight = this.page.height();
    
    this.buffer.stop();
    this.buffer.css({
      display: "block",
      position: "absolute"
    });
    var bufferHeight = this.buffer.height();
    
    if (bufferHeight >= pageHeight) {
      // Buffer is taller than the current page - fade it in
      this.container.css("height", bufferHeight);
      
      this.page.css({
        opacity: 1,
        zIndex: 0
      });
      this.buffer.css({
        opacity: 0,
        zIndex: 1
      });
      this.buffer.animate(
        {opacity: 1},
        duration,
        function() {
          _this.page.css({
            filter: ""
          });
          _this.buffer.css({
            opacity: 0,
            display: "none",
            position: "absolute"
          });
          _this.container.css("height", _this.page.height());
        }
      );
    } else {
      // Current page is taller than the buffer - fade it out
      this.container.css("height", pageHeight);
      
      this.page.css({
        opacity: 1,
        zIndex: 1
      });
      this.buffer.css({
        opacity: 1,
        zIndex: 0
      });
      this.page.animate(
        {opacity: 0},
        duration,
        function() {
          _this.page.css({
            filter: ""
          });
          _this.buffer.css({
            opacity: 0,
            display: "none",
            position: "absolute"
          });
          _this.container.css("height", _this.page.height());
        }
      );
    }
  }
  
  var buffer = this.buffer;
  this.buffer = this.page;
  this.page = buffer;
};

function PageContainer(parent) {
  if (parent == null)
    return;
  if (parent.length <= 0)
    return;
  
  this.parent = parent;
  this.container = $(document.createElement("div")).css({
    position: "relative",
    overflow: "hidden"
  });
  
  var pageCSS = {
    position: "absolute",
    backgroundColor: "white",
    top: 0,
    left: 0,
    opacity: 0,
    display: "none"
  };
  
  this.page = $(document.createElement("div")).css(pageCSS);
  this.buffer = $(document.createElement("div")).css(pageCSS);
  
  this.container.append(this.page);
  this.container.append(this.buffer);
  this.parent.append(this.container);
}

$("document").ready(function() {
  // Create image shadows
  var images = $("img.shadowed");
  images.css("visibility", "hidden");
  
  var createShadowFunction = function(image) {
    return UIUtilities.createImageWaitFunction(image, function(image) {
      image = $(image);
      var width = image.attr("width");
      var height = image.attr("height");
      var src = image.attr("src");
      if (width == null || height == null || src == null)
        return;
      var parent = image.parent();
      if (parent.length <= 0)
        return;
      
      // Rig alt text to appear via title attribute, if necessary
      var altText = image.attr("alt");
      if (altText != null) {
        var titleText = image.attr("title");
        if (titleText == null || titleText == "")
          image.attr("title", altText);
      }
      
      var shadow = UIUtilities.createShadowDiv(width, height);
      
      var elem;
      if (parent[0].nodeName.toLowerCase() == "a") {
        // The image is inside a link - move the entire link into the shadow container
        elem = parent;
        parent.before(shadow);
        shadow.append(parent);
      } else {
        // The image doesn't appear to be inside a link - just move it into the shadow container
        elem = image;
        image.before(shadow);
        shadow.append(image);
      }
      
      image.css({
        visibility: "visible"
      });
      
      elem.css({
        position: "absolute",
        top: UIUtilities.Shadow.BlurRadius - UIUtilities.Shadow.Offset,
        left: UIUtilities.Shadow.BlurRadius - UIUtilities.Shadow.Offset
      });
    });
  };
  
  for (var i=0; i<images.length; i++) {
    var waitFunction = createShadowFunction(images[i]);
    waitFunction();
  }
  
  // Fix subject matter expert PNGs in IE6
  // and fix other PNGs in IE6, added by Brian Sinnett, 2/26/10
  UIUtilities.fixImages("img.expert-photo, img.ie6PngFix");

  // Add arrow links
  var arrowlinks = $("a.arrowed");

  for (var i=0; i<arrowlinks.length; i++) {
    $(arrowlinks[i]).append('&nbsp;<img src="/en_GX/webadmin/assets/image/orange_arrow.gif"/>');
  }
  
  // Set up accordions
  Accordion.init();
  
  // Set up modals
  Modal.init();
  
  // Set up contextual popups
  ContextualPopupController.init();
  
});

