// From prototype.js
// Extending Object breaks jQuery UI
//Object.prototype.isFunction = function(object) {
//    return typeof object == "function";
//  };

String.interpret = function(value) {
    return value == null ? '' : String(value);
  };

String.prototype.startsWith = function(pattern) {
    return this.indexOf(pattern) === 0;
  };

String.prototype.gsub = function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  };

String.prototype.gsub.prepareReplacement = function(replacement) {
//  if (Object.isFunction(replacement)) return replacement;
  if (jQuery.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
};

var Template = function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  };

Template.prototype.evaluate = function(object) {
//    if (Object.isFunction(object.toTemplateReplacements))
    if (jQuery.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return '';

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3];
      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }

Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

// Other Functions


(function($){

  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
	$.fn.toc = function(source, options) {
    options = $.extend({}, $.fn.toc.defaults, options);
		var li_content = "";
	  $(options.selector, source).each(function(){
			var $contentElement = options.contentSelector ? $(options.contentSelector, $(this)) : $(this);
			var content = options.attr ? $contentElement(options.attr) : $contentElement.html();
		  if (content) li_content = li_content + options.template.evaluate({href: "#" + this.id, content: content}); 
		});
		if (options.clear) {
		  return this.html(li_content);
		} else if (options.prepend) {
		  return this.prepend(li_content);
		} else {
		  return this.append(li_content);
		}
	}
	$.fn.toc.defaults = { prepend:false, selector:"dt", clear:false, attr:null, contentSelector:null, template: new Template('<li><a href="#{href}">#{content}</a></li>') };
	
  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.fn.pipelist = function(options) {
    options = $.extend({}, $.fn.pipelist.defaults, options);
		var links = $("a", this);
		if (options.href == "id") {
			links.each(function() {this.href = "#" + this.id;});
		} else if (options.href == "void") {
			links.attr("href", "javascript:void(0)");
		} else if (options.href){
			links.attr("href", options.href);
		}
		if (options.target) {
			links.attr("target", options.target);
		}
		if (options.click) {
			links.click(function() {options.click(this, links)});
		}
		$("li:gt(0)", this).prepend(options.pipe);
		return this;
	}				
	$.fn.pipelist.defaults = { pipe: "&#124;&nbsp;", click:null, href:null, hrefFromAttr:null, target:null };
	
  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.fn.ieFocus = function(options) {
    options = $.extend({}, $.fn.ieFocus.defaults, options);
		$(":input:not(:button):not(:submit):not(:radio):not(:checkbox)", $(this))
			.addClass(options.blurClassName)
			.focus(function() {$(this).addClass(options.focusClassName).removeClass(options.blurClassName);})
			.blur(function() {$(this).addClass(options.blurClassName).removeClass(options.focusClassName);})
			.change(function() {$(this).addClass(options.blurClassName).removeClass(options.focusClassName);});
		return this;
  }
 	$.fn.ieFocus.defaults = { focusClassName:"sfFocus", blurClassName:"sfBlur" };

  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.htmlTemplate = function (url, callback) {
		var responseText = "";
		if (url.indexOf("#") == 0) {
			var template = $(url).html().replace(/#%7B(\w{1,32})%7D/g, "#{$1}"); // Firefox converts #{xxx} to %7Bxxx%7D
			callback(new Template(template));
		} else {
		  var successFunction = function(responseText) {callback(new Template(responseText || ""))};
		  if (url.indexOf("http") == 0) {
		  	$.ajax({"url": "/proxy", "data": {".serviceUrl." : url}, "timeout": 10000, "success": successFunction});
		  } else {
			  $.ajax({"url": url, "timeout": 10000, "success": successFunction});
		  }
		}
	}

  $.fn.htmlTemplate = function () {
		var template = this.html().replace(/#%7B(\w{1,32})%7D/g, "#{$1}"); // Firefox converts #{xxx} to %7Bxxx%7D
		return new Template(template);
	}

  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.defaultLocale = function() {
    var locale = navigator.language || navigator.browserLanguage;
    locale = locale ? locale.toLowerCase() : "";
		var language = (locale.length >= 2) ? locale.substring(0,2) : "";
		var country  = (locale.length >= 5) ? locale.substring(3,5) : "";
		return {language: language, country: country, locale: locale};
  }

  var pathPrefix = "../../";
  $.browserLocale = function(callback, options) {
    options = $.extend({}, $.browserLocale.defaults, options);
    if ((!options.ajax) || (window.location.protocol == "file:")) {
	  	callback($.defaultLocale(), "success");
	  } else {
	    $.getJSON(pathPrefix + options.ajaxPath, {method:"get", cache:false, timeout:10000}, callback);
		}
	}
	$.browserLocale.defaults = { ajaxPath:"locale.jsp", ajax:false };

  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.viewportWidth = function() {
     return self.innerWidth ||  $.boxModel && document.documentElement.clientWidth || document.body.clientWidth;
	}
	
  $.viewportHeight = function() {
     return self.innerHeight ||  $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
	}

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  FlashPlayer = function(movieName) {
    this.player = document[movieName] || window[movieName];
	}
	
	FlashPlayer.prototype.available = function() {
			$.dump(this.player);
		return (this.player != null) && (this.player.PercentLoaded != undefined);
	}
	
	FlashPlayer.prototype.play = function() {
	  if (this.available() && (this.player.PercentLoaded() == 100)) {
			this.player.Play();
		}
	}
	
	FlashPlayer.prototype.stop = function() {
		if (this.available() && (this.player.IsPlaying())) {
			this.player.StopPlay();
		}
	}
	
	FlashPlayer.prototype.rewind = function() {
	  if (this.available() && (this.player.PercentLoaded() == 100)) {
			this.player.StopPlay();
			this.player.Rewind();
		}
	}

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------

	$.fn.button = function(options) {
    options = $.extend({}, $.fn.button.defaults, options);
		
	  return this.each(function() {
			this.options = options;
			this.disabled = !options.enabled;
			this.enable = $.fn.button.enable;
			this.disable = $.fn.button.disable;
			if (this.disabled) {
				$.fn.button.disable(this);
			} else {
				$.fn.button.enable(this);
			};
			
			$(this)
			  .hover( function() {if (!this.disabled) this.className = options.mouseOverClassName},	
								function() {if (!this.disabled) this.className = options.enabledClassName})
			  .mousedown(function() {if (!this.disabled) this.className = options.pressedClassName})
			  .mouseup(  function() {if (!this.disabled) this.className = options.enabledClassName});
    });	
  };

	$.fn.button.defaults = {
		enabled: true,
		enabledClassName: "buttonEnabled",
		disabledClassName: "buttonDisabled",
		mouseOverClassName: "buttonMouseOver",
		pressedClassName: "buttonPressed"
	};

  $.fn.button.enable = function (element) {
		element.disabled = false;
		element.className = element.options.enabledClassName;
  };

  $.fn.button.disable = function(element) {
		element.disabled = true;
		element.className = element.options.disabledClassName;
  };

  
  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
  $.fn.enable = function () {
	  return this.each(function() {
		  if(this.enable) {
			  this.enable(this);
			} else {
        this.disabled = false; 
 		  }
		})
	};
  $.fn.disable = function () {
	  return this.each(function() {
		  if(this.disable) {
			  this.disable(this);
			} else {
        this.disabled = true; 
 		  }
	  })
	};

  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------
	
	$.fn.accordionMenu = function() {
		  var $drawers = this;
			
			var $accordion = $drawers.accordion({
		    animated: false,
				active: 0,
		    navigation: true,
				header: "h2.drawer-handle",
				selectedClass: "open",
				event: "mouseover click"
		}).focus(function() {if(this.blur) this.blur();});
			
		return $accordion;
}
	
  //---------------------------------------------------------------------------------------------------------------------------------------------------------------------

  $.fn.tabMenu = function (options) {
		
      options = $.extend({}, $.fn.tabMenu.defaults, options);
			
      var $menu = this;
			var $menu_ul = $("> ul.tab", $menu);
			var $menu_lis = $("> li", $menu_ul);
			
			var $panels = $("> div", $menu);
			var $panel_ul = $("> ul", $panels);

			var $panelAnchors = $("> li > a", $panel_ul);
			var $currentAnchor = $panelAnchors.filter(function() {return this.href.toLowerCase() == location.href.toLowerCase()});
			
			var selectedTabIndex = 0;
			if ($currentAnchor.length) {
				$currentAnchor = $($currentAnchor[0]);
				$currentAnchor.css(options.cssCurrentAnchor);
      	var $currentPanel = $currentAnchor.parent().parent().parent();
	  		selectedTabIndex = $panels.index($currentPanel);
			}

      var $tabs = $menu_ul.tabs({event: "mouseover", selected: selectedTabIndex});
			
			var $tabAnchors = $("> a", $menu_lis);
			var $allAnchors = $tabAnchors.add($panelAnchors);
			$allAnchors.hover(function(){$(this).css(options.cssAnchorFocus)}, function(){$(this).css(options.cssAnchorBlur)});
				
			$panel_ul.pipelist();
		
      $menu_ul = $menu_ul.tabs("add", "#empty_panel", ""); 
      var lastTabIndex = $menu_ul.tabs("length") - 1;
			$menu_ul.tabs("disable", lastTabIndex);

      var $disabled_li = $($("> li", $menu_ul)[lastTabIndex]);
			var $disabled_a = $("> a", $disabled_li);
			$disabled_a.hover(function(){$menu_ul.tabs("select", selectedTabIndex)}, function(){});
			$disabled_a.css({"background-image":"none"});
			$("> span", $disabled_a).css({"background-image":"none","width":"580px"});
			
      $menu.hover(function() {
				 selectedTabIndex = $tabs.data("selected.tabs");
			 },
			 function() {
				 $menu_ul.tabs("select", selectedTabIndex);			
			 }
			);
			
			var loadPage = function() { 
				var nextPage = $("> ul > li > a", $(this.hash))[0].href;
				window.location.replace(nextPage);
			} 
			
			$tabAnchors.click(loadPage);
			
			return $tabs;
	}
	$.fn.tabMenu.defaults = {
		cssAnchorFocus:   {"text-decoration": "underline"},
		cssAnchorBlur:    {"text-decoration": "none"},
		cssCurrentAnchor: {"color": "black"}
	};
	
//---------------------------------------------------------------------------------------------------------------------------------------------------------------------

  // Removes event handlers to prevent memory leaks in IE6 and lower
	// See http://www.crockford.com/javascript/memory/leak.html
	$.fn.clearEvents_IE = function() {
	  if ($.browser.msie && ($.browser.version <= 7)) {
	    return this.each(function() {clearEvents(this)});
		} else {
		  return this;
		} 
	}

  clearEvents = function (element) {
    var attributes = element.attributes;
 	  if (attributes) {
		  for (var i = 0, n = attributes.length; i < n; ++i) {
		    var name = attributes[i].name;
	   	  if (typeof element[name] === 'function') {
		      element[name] = null;
		    }
	    }    
	  }
	  var children = element.childNodes;
	  if (children) {
		  for (var i = 0, n = children.length; i < n; ++i) {
		    clearEvents(children[i]);
	    }
    }
  }

})(jQuery);

//---------------------------------------------------------------------------------------------------------------------------------------------------------------------
