/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 4187 2007-12-16 17:15:27Z joern.zaefferer $
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName )
					return undefined;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);
var Remove_Links = {

	links: jQuery("a[href='']:not([name])"),
	
	initialize: function() {
	
		var self = Remove_Links;
	
		if (!self.links.length) {
			return false;
		}
		
		self.links.remove();
	
	}

}
Remove_Links.initialize();

var Forms = {
  initialize: function() {
    this.addValidationRules();
    this.formValidate();
  },

  addValidationRules: function() {

    jQuery.validator.addMethod("title", function(value, element, params) { 
      return value != 0;
    }, "<br/>Please select your Title");

	jQuery.validator.addMethod("dob", function(value, element) { 
	  
		var name = element.name.split("[");
		
		if (name.length === 2) {
			name = name[0];
		}
		else {
			return true;
		}
			
		var day = parseFloat(jQuery("*[name='" + name + "[d]']").val());
		var month = parseFloat(jQuery("*[name='" + name + "[m]']").val())
		var year = parseFloat(jQuery("*[name='" + name + "[y]']").val())
		
		if (day === "" || month === "" || year === "") {
			return true;
		}
		
		if (isNaN(day) || isNaN(month) || isNaN(year)) {
			return true;
		}
		
		var y = parseInt(year / 4) * 4; 
		
		var error_31 = day === 31 & (month === 2 || month === 4 || month === 06 || month === 09 || month === 11);
		var error_29 = day === 29 & month === 2 & year !== y; 	
		
		if (error_31) {
			return false;
		}
		
		if (error_29) {
			return false;
		}
		
		return true;
	 
	}, "Please specify a correct date");

  },

  formValidate: function() {
    jQuery("form").each(function() { 
      jQuery(this).validate(); 
    });
  }
}

Forms.initialize();

var TheSource = {

  initialize: function() {

    var param = this.getParam("theSource");
    var override = this.getParam("Override")
    var hear = jQuery("#hear-about-us");
    var cookie = this.getCookie("theSource");
    var self = TheSource;

    if(param != "") {
      if(cookie == "" || override == "1") {
        this.setCookie("theSource", param, 90, "/", ".h-l.co.uk", "");
      }
    }

	if(typeof(client_details) !== "undefined" && client_details !== "") {
      	this.setCookie("theSource", "WWWLI", 90, "/", ".h-l.co.uk", "");
    }

    cookie = this.getCookie("theSource");

    if(cookie != "")
    {
      jQuery("#hear-about-us").hide();
	  jQuery(".theSource_1").append("<option value='" + cookie + "'>" + cookie + "</option>");
      jQuery(".theSource_1 option:last").attr("selected", "true");
    }

    if(hear.length !== 0)
    {
      var form = hear.parents("form:first");
      form.submit(function() {
          self.setCookie("theSource", jQuery(".theSource_1").val(), 90, "/", ".h-l.co.uk", "");
      });
    }
  },

  setCookie: function Set_Cookie( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var expires_date = new Date();
    expires_date.setDate(expires);

    document.cookie = name + "=" +escape( value ) + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + ( ( path ) ? ";path=" + path : "" ) + ( ( domain ) ? ";domain=" + domain : "" ) + ( ( secure ) ? ";secure" : "" );
  },

  getCookie: function(c_name) {
    if (document.cookie.length > 0) {
      c_start=document.cookie.indexOf(c_name + "=");
      if(c_start != -1)
      {
        c_start = c_start + c_name.length + 1; 
        c_end = document.cookie.indexOf(";",c_start);
        
        if(c_end == -1)
        {
          c_end = document.cookie.length;
        }

        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    
    return "";
  },

  getParam: function(param) {
    var value = "";
    var param_list = location.toString().split("&");
    
    for(i = 0; i < param_list.length; i++) 
    {
      if(param_list[i].search(param) != -1)
      {
        value = param_list[i].split("=")[1];
      }
    }
    
    return value;
  }
}

TheSource.initialize();

var PostcodeChecker = {
  pc_label: jQuery("#address-container-label"),
  pc_input: jQuery(".address_postcode"),
  pc_container: jQuery("#postcode-container"),
  pc_button: jQuery("#postcode-checker"),
  pc_info: jQuery("#postcode-info"),
  address_details: jQuery("#address-details"),
  address_details_manual: jQuery("#address-details-manual"),
  additional_details: jQuery("#additional-details"),
  address_container_info: jQuery("#address-container-info"),
  postcode_info: jQuery("#postcode-info"),
  form_submit: jQuery("#form-submit"),
  pc_url: location.protocol + "//www.h-l.co.uk/ajax/postcode-checker",

  initialize: function() {
    var self = PostcodeChecker;

    // check to see if client details have been nested in the page
    if(typeof(client_details) !== "undefined" && client_details !== "")
    {
      self.autocomplete(client_details);
      return false;
    }

    self.address_details_manual.hide();
    self.additional_details.hide();
    // self.form_submit.hide();
    self.pc_button.css("display", "inline");
    self.pc_input.css("float", "left");
    self.pc_info.css("display", "block");
    self.pc_button.click(self.pc_click);
    self.pc_container.change(self.pc_change);
    self.address_container_info.click(self.pc_manual_click);
    self.postcode_info.children("span").click(self.pc_manual_click);
  },

  autocomplete: function(client_details) {



//function to read a value from the cookie
function readCookie(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;
}

// sets reg details to one
jQuery("#content form #personal-details").append('<input type="hidden" value="1" name="use_reg_details" />');

// gets the client number from the cookie
jQuery("#content form #personal-details").append('<input type="hidden" value="' + client_details.clientNumber + '" name="client_num" />');



    // handle the text fields
    var text_form_fields = ["title","forenames","surname","email","postCode","phoneDaytime","phoneEvening"];    
    for(var i = 0; i < text_form_fields.length; i++)
    {
      if(jQuery("." + text_form_fields[i]).val() === "" && client_details[text_form_fields[i]] !== "")
      {
        jQuery("." + text_form_fields[i]).val(client_details[text_form_fields[i]]);

         // if user is logged in, replace the form fields with hidden input and print the input values
         var tempStoreId = jQuery("." + text_form_fields[i]).attr('id');
         jQuery("." + text_form_fields[i]).after(   jQuery("." + text_form_fields[i]).attr('value')   );
         jQuery("." + text_form_fields[i]).before('<input type="hidden" value="' + jQuery("." + text_form_fields[i]).attr('value') + '" name="' + jQuery("." +         text_form_fields[i]).attr('name') + '" id="tempID" />');
         jQuery("." + text_form_fields[i]).remove();
         jQuery('#tempID').attr('id',tempStoreId);

      }

    }

    // handle the address lines
    var i = 1;
    for(var j = 0; j < client_details.address.length; j++)
    {
      if(jQuery(".address" + i).val() === "")
      {
		if( client_details.address[j] !== "" ){
 	         jQuery(".address" + i).val(client_details.address[j]);

	         // if user is logged in, replace the form fields with hidden input and print the input values (for address fields)
	         var tempStoreId = jQuery(".address" + i).attr('id');
	         jQuery(".address" + i).after(   jQuery(".address" + i).attr('value')   );
	         jQuery(".address" + i).before('<input type="hidden" value="' + jQuery(".address" + i).attr('value') + '" name="' + jQuery(".address" + i).attr('name') + '" id="tempID" />');
	         jQuery(".address" + i).remove();
	         jQuery('#tempID').attr('id',tempStoreId);
  		}
        i++;
      }
    }

    var l = client_details.address.length;
    for( var k = 0; k < 5 - client_details.address.length; k++) {
        l++;
        jQuery(".address" + l ).parent().remove();
    }
    


    
  },

  pc_click: function() {
    var self = PostcodeChecker;
    self.address_fill_with("#######".split("#"));			
    self.pc_input.addClass("loading");
    self.pc_label.text("Please wait, loading...");
    self.pc_container.animate({opacity: 0.5});
    self.pc_container.children("option").click(function() {
      jQuery(this).removeAttr("selected").blur();
      return false;
    });
    self.postcode_info.slideUp(500);
    self.address_details_manual.slideUp(500);
    self.call_ajax(self.pc_input.val());
  },

  pc_change: function() {
    var self = PostcodeChecker;
    self.address_fill_with(self.pc_container.val().toString().split(", "));
    self.additional_details.slideDown(500, function() {
      //self.form_submit.slideDown(500);
      //jQuery('#additional-details #hear-about-us h2').hide();
      //jQuery('#additional-details #hear-about-us').show();
    });
  },

  call_ajax: function(value) {
    var self = PostcodeChecker;
    jQuery.ajax({
      url: self.pc_url + "?postcode=" + value,
      dataType: "json",
      success: function(data) {
        var i = 0;
        self.pc_container.empty();

        if(data.SStatus == "N")
        {
          self.pc_label.text("Postcode not found");
        }
        else
        {
          while((typeof(data[i])!="undefined"))
          {
            var address = data[i].PartialAddress.split(", ");
            address.pop();
            address = address.toString().replace(/,/g, ", ");
            self.pc_container.append('<option value="'+address+'">'+address+'</option>');
            ++i;
          }		
          self.pc_label.text("Highlight your address below");	
        }

        self.pc_input.removeClass("loading");
        self.pc_container.animate({opacity: 1});
        self.address_details.slideDown(500);
      },
      error: function() {
        self.pc_input.removeClass("loading");
        self.pc_manual_click();
      }
    });
  },

  pc_manual_click: function() {
    var self = PostcodeChecker;

    //jQuery('#additional-details #hear-about-us h2').hide();
    //jQuery('#additional-details #hear-about-us').show();

    self.address_fill_with("#######".split("#"));
    self.postcode_info.slideUp(500);
    self.address_details.slideUp(500, function() {
      self.address_details_manual.slideDown(500, function() {
        self.additional_details.slideDown(500, function() {
          // self.form_submit.slideDown(500);
        });
      });
    });
  },

  address_fill_with: function(values) {
    jQuery(values).each(function(i) {
      if(i > 4)
      {
        return false;
      }
      
      jQuery("#address-details-manual input:eq(" + i + ")").val(this);
    });
  }
}

PostcodeChecker.initialize();
/*
	facebox v1.1.5 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
	(c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
	Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

(function(jQuery){
var clone, loadedWidth, loadedHeight, interfaceHeight, interfaceWidth, index, related, closeModal, loadingElement, modal, modalWrap, modalOverlay, modalLoadingOverlay, modalContent, loaded, modalClose, btc, bml, bmr, bbc;
function setModalOverlay(){
	jQuery([modalOverlay]).css({"position":"absolute", width:jQuery(window).width(), height:jQuery(window).height(), top:jQuery(window).scrollTop(), left:jQuery(window).scrollLeft()});
}
function keypressEvents(e){
	if(e.keyCode == 37){
		jQuery(document).unbind('keydown.colorKeys');
		jQuery("a#contentPrevious").click();
	} else if(e.keyCode == 39){
		jQuery(document).unbind('keydown.colorKeys');
		jQuery("a#contentNext").click();
	}
}
function clearLoading(){
	if(jQuery("#faceboxInlineTemp").length > 0){
		jQuery(loaded).children().insertAfter("#faceboxInlineTemp");
	}
	if(loadingElement){jQuery(loadingElement).remove();}
}

closeModal = function(){
	clearLoading();
	jQuery(modal).stop(true, false).removeData("open").fadeOut("slow", function(){
		jQuery(modalOverlay).fadeOut("fast");
		jQuery(loaded).remove();
	});
	jQuery(document).unbind('keydown.colorKeys');
	jQuery(window).unbind('resize scroll', setModalOverlay);
	// re enable scrolling on the page when the facebox is closed
	jQuery("body").removeClass("facebox-overflow").removeClass("facebox-overflow-padding");
  	jQuery("html").removeClass("facebox-overflow");
};

// Convert % values to pixels
function setSize(size, dimension){
	return (typeof size == 'string') ? (size.match(/%/) ? (dimension/100)*parseInt(size, 10) : parseInt(size, 10)) : size;
}

//Initialize the modal: store common calculations, preload the interface graphics, append the html.
jQuery(function(){
	jQuery("body").append(
		jQuery([
			modalOverlay = jQuery('<div id="modalBackgroundOverlay" />')[0], 
			modal = jQuery('<div id="facebox" />')[0]
		]).hide()
	);
	jQuery(modal).append(
		jQuery([
			modalWrap = jQuery('<div id="modalWrap" />')[0]
		])
	).css("opacity", 0).show();
	jQuery(modalWrap).append(
		jQuery([
			jQuery('<div><div id="borderTopLeft"></div><div id="borderTopCenter"></div><div id="borderTopRight"></div></div>')[0],
			bml = jQuery('<div id="borderMiddleLeft" />')[0],
			modalContent = jQuery('<div id="modalContent" />')[0],
			bmr = jQuery('<div id="borderMiddleRight" />')[0],
			jQuery('<div><div id="borderBottomLeft"></div><div id="borderBottomCenter"></div><div id="borderBottomRight"></div></div>')[0]
		])
	);
	jQuery(modalContent).append(
		jQuery([
			loaded = jQuery('<div id="modalLoadedContent"><a id="contentPrevious" href="#"></a><a id="contentNext" href="#"></a><span id="contentCurrent"></span><br id="modalInfoBr"/><span id="contentTitle"></span><div id="preloadPrevious"></div><div id="preloadNext"></div><div id="preloadClose"></div></div>')[0], 
			modalLoadingOverlay = jQuery('<div id="modalLoadingOverlay" />')[0],
			modalClose = jQuery('<a id="modalClose" href="#"></a>')[0]
		])
	);

	jQuery(document).bind("keydown.colorClose", function(e){
		if (e.keyCode == 27) { closeModal(); }
	});

	jQuery(modalClose).click(function(){
		closeModal();
		return false;
	});

	btc = jQuery("#borderTopCenter")[0];
	bbc = jQuery("#borderBottomCenter")[0];

	interfaceHeight = jQuery(btc).height()+jQuery(bbc).height()+jQuery(modalContent).outerHeight(true) - jQuery(modalContent).height();//Subtraction needed for IE6
	interfaceWidth = jQuery(bml).width()+jQuery(bmr).width()+jQuery(modalContent).outerWidth(true) - jQuery(modalContent).width();

	loadedHeight = jQuery(loaded).outerHeight(true);
	loadedWidth = jQuery(loaded).outerWidth(true);

	jQuery(loaded).empty();
	jQuery(modal).css({"padding-bottom":interfaceHeight,"padding-right":interfaceWidth}).hide();//the padding removes the need to do size conversions during the animation step.

	//Archaic rollover code because IE8 is a piece of shit.  Hopefully they'll fix their css-rollover bug so the following code can be removed.
	jQuery("#contentPrevious, #contentNext, #modalClose").live('mouseover', function(){jQuery(this).addClass("hover");});
	jQuery("#contentPrevious, #contentNext, #modalClose").live('mouseout', function(){jQuery(this).removeClass("hover");});
});

jQuery.fn.facebox = function(settings, callback) {
    
	function modalPosition(mWidth, mHeight, speed, loadedCallback){
	
		var winHeight = document.documentElement.clientHeight;
		var posTop = winHeight/2 - mHeight/2 + jQuery(window).scrollTop();
		var posLeft = document.documentElement.clientWidth/2 - mWidth/2 + jQuery(window).scrollLeft();
		//keeps the box from expanding to an inaccessible area offscreen.
		if(mHeight > winHeight){posTop -=(mHeight - winHeight);}
		if(posTop < 0){posTop = 0;} 
		if(posLeft < 0){posLeft = 0;}
	
		mWidth = mWidth - interfaceWidth;
		mHeight = mHeight - interfaceHeight;
	
		function modalDimensions(that){
			modalContent.style.width = btc.style.width = bbc.style.width = that.style.width;
			modalContent.style.height = bml.style.height = bmr.style.height = that.style.height;
		}
	
		jQuery(modal).animate({height:mHeight, width:mWidth, top:posTop, left:posLeft}, {duration: speed,
			complete: function(){
				if (loadedCallback) {loadedCallback();}
				modalDimensions(this);
				if (jQuery.browser.msie && jQuery.browser.version < 7) {setModalOverlay();}
			},
			step: function(){
				modalDimensions(this);		
			}
		});
	}
	
	function disableScroll() {
		if (!settings.scroll) {
			jQuery("body").addClass("facebox-overflow");
		  	jQuery("html").addClass("facebox-overflow");
			
			if (jQuery(document).height() > jQuery(window).height()) {
				jQuery("body").addClass("facebox-overflow-padding");
			}
			
		}
	}
	
	var preloads = [];
	function preload(){
		if(settings.preloading !== false && related.length>1 && related[index].href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?jQuery/i)){
			var previous, next;
			previous = index > 0 ? related[index-1].href : related[related.length-1].href;
			next = index < related.length-1 ? related[index+1].href : related[0].href;
			return [jQuery("<img />").attr("src", next), jQuery("<img />").attr("src", previous)];
		}
		return false;
	}
	
	function contentNav(){
		jQuery(modalLoadingOverlay).show();
		if(jQuery(this).attr("id") == "contentPrevious"){
			index = index > 0 ? index-1 : related.length-1;
		} else {
			index = index < related.length-1 ? index+1 : 0;
		}
		loadModal(related[index].href, related[index].title);
	}
	
	function centerModal (object, contentInfo){
		if(jQuery(modal).data("open")!==true){ return false; }

		var speed = settings.transition=="none" ? 0 : settings.transitionSpeed;
		jQuery(loaded).remove();
		loaded = jQuery(object)[0];
	
		jQuery(loaded).hide()
		.css({width:(settings.fixedWidth)?settings.fixedWidth - loadedWidth - interfaceWidth:jQuery(loaded).width()}).css({height:(settings.fixedHeight)?settings.fixedHeight - loadedHeight - interfaceHeight:jQuery(loaded).height()})
		.attr({id:"modalLoadedContent"})
		.append(contentInfo)
		
		setTimeout(function() {
			jQuery(loaded).prependTo(jQuery(modalContent));
		}, settings.transitionSpeed);
		

		if(jQuery("#modalPhoto").length > 0 && settings.fixedHeight){
			var topMargin = (parseInt(jQuery(loaded)[0].style.height, 10) - parseInt(jQuery("#modalPhoto")[0].style.height, 10))/2;
			jQuery("#modalPhoto").css({marginTop:(topMargin > 0?topMargin:0)});
		}
	
		function setPosition(s){
			modalPosition(parseInt(loaded.style.width, 10)+loadedWidth+interfaceWidth, parseInt(loaded.style.height, 10)+loadedHeight+interfaceHeight, s, function(){
				if(jQuery(modal).data("open")!==true){
					return false;
				}
				jQuery(loaded).show();
				jQuery(document).bind('keydown.colorKeys', keypressEvents);
				if (callback) {
					callback();
				}
				if (settings.transition === "fade"){
					jQuery(modal).animate({"opacity":1}, speed);
				}
				return true;
			});
		}
		if (settings.transition == "fade") {
			jQuery(modal).animate({"opacity":0}, speed, function(){setPosition(0);});
		} else {
			setPosition(speed);
		}
		var preloads = preload();
		return true;
	}
	
	function loadModal(href, title, content){
		clearLoading();
			
		var contentInfo = "<p id='contentTitle'></p>";
		if(related.length>1){
			contentInfo += "<span id='contentCurrent'> " + settings.contentCurrent + "</span>";
			contentInfo = contentInfo.replace(/\{current\}/, index+1).replace(/\{total\}/, related.length);
			contentInfo += "<div class='remove-nav'><a id='contentPrevious' href='#'>"+settings.contentPrevious+"</a><a id='contentNext' href='#'>"+settings.contentNext+"</a></div> ";
		}
		if (settings.inline) {
			loadingElement = jQuery('<div id="faceboxInlineTemp" />').hide().insertBefore(jQuery(href)[0]);
			clone = jQuery(href).clone(true);
			centerModal(jQuery(href).wrapAll("<div />").parent(), contentInfo);
			finishLoad();
		} else if (settings.string) {
			centerModal(content, contentInfo);
			finishLoad();
		} else if (settings.iframe) {
			centerModal(jQuery("<div><iframe id='modalIframe' name='iframe_"+new Date().getTime()+" 'frameborder=0 src =" + href + "></iframe></div>"), contentInfo);//timestamp to prevent caching.
			setTimeout(function() {
				jQuery("#modalIframe").load(function() {
					finishLoad();
				});
			}, settings.transitionSpeed);
		} else if (settings.form) {
				var form = jQuery(settings.form).parents("form:first");		
				centerModal(jQuery("<div><iframe id='modalIframe' name='modalIframe' frameborder='0'></iframe></div>"), contentInfo);//timestamp to prevent caching.
				setTimeout(function() {
					form.attr("target", 'modalIframe');
					form.append(settings.form.clone())
					if (settings.action) {
						form.attr("action", settings.action)
					}
					form.find("input.facebox:last, button.facebox:last").click().remove();
					jQuery("#modalIframe").load(function() {
						finishLoad();
					});
				}, settings.transitionSpeed);
		} else if (href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?jQuery/i)){
			loadingElement = new Image();
			loadingElement.onload = function(){
				loadingElement.onload = null;
				centerModal(jQuery("<div />").css({width:this.width, height:this.height}).append(jQuery(this).css({width:this.width, height:this.height, display:"block", margin:"auto"}).attr('id', 'modalPhoto')), contentInfo);
				if(related.length > 1){
					jQuery(this).css({cursor:'pointer'}).click(contentNav);
				}
				finishLoad();
			};
			loadingElement.src = href;
		}else {
			loadingElement = jQuery('<div />').load(href, function(data, textStatus){
				if(textStatus == "success"){
					centerModal(jQuery(this), contentInfo);
				} else {
					centerModal(jQuery("<p>Request unsuccessful.</p>"));
				}
			});
		}
	}
	
	function finishLoad() {
		jQuery(".remove-nav").remove();
		jQuery("#contentCurrent").remove();
		jQuery(modalLoadingOverlay).fadeOut(parseInt(settings.transitionSpeed/2));
				
				var iframe_loaded = jQuery(modal).find("iframe:first");

				/*if (iframe_loaded.length) {

					var iframe_name = iframe_loaded.attr("name");

					if (iframe_name !== "") {

						var top_loc = top.document.location;
						
						var doc_loc = top.frames[iframe_name].location;

						if (top_loc.host === doc_loc.host && top_loc.protocol === doc_loc.protocol) {

							iframe_loaded.contents().find(".close-facebox").click(function() {
								closeModal(); return false;
							});

						}

					}

				}*/
				
				try {
					iframe_loaded.contents().find(".close-facebox").click(function() {
						closeModal(); return false;
					});
				}
				catch(err) {
				}

                jQuery(modal).find(".close-facebox").click(function() {
                 	closeModal(); return false;
                });
	}

	settings = jQuery.extend({}, jQuery.fn.facebox.settings, settings);
	
	jQuery(this).unbind("click.facebox").bind("click.facebox", function () {
			
		if (settings.form) {
				var form = jQuery(settings.form).parents("form:first");
				if (!form.valid()) {
					return false;
				}
		}
		
		if(settings.fixedWidth){ settings.fixedWidth = setSize(settings.fixedWidth, document.documentElement.clientWidth);}
		if(settings.fixedHeight){ settings.fixedHeight = setSize(settings.fixedHeight, document.documentElement.clientHeight);}
		if (this.rel && 'nofollow' != this.rel) {
			related = jQuery("a[rel='" + this.rel + "']");
			index = jQuery(related).index(this);
		}
		else {
			related = jQuery(this);
			index = 0;
		}

		if (jQuery(modal).data("open") !== true) {
			jQuery(document).bind('keydown.colorKeys', keypressEvents);
			jQuery(modalClose).html(settings.modalClose);
			jQuery(modalOverlay).css({"opacity": settings.bgOpacity});
			jQuery(modal).data("open", true).css({"opacity":1});
			jQuery([modal, modalLoadingOverlay, modalOverlay]).show();

			modalPosition(setSize(settings.initialWidth, document.documentElement.clientWidth), setSize(settings.initialHeight, document.documentElement.clientHeight), 0);

			if (jQuery.browser.msie && jQuery.browser.version < 7) {
				jQuery(window).bind("resize scroll", setModalOverlay);
			}
		}

		disableScroll();	
		
		setTimeout(function() {
			loadModal(settings.href ? settings.href : related[index].href, settings.title ? settings.title : related[index].title, settings.ajaxContent);
		}, parseInt(settings.transitionSpeed/2))
		
		jQuery("a#contentPrevious, a#contentNext").die().live("click", contentNav);

		if(settings.overlayClose!==false){
			jQuery(modalOverlay).css({"cursor":"pointer"}).click(function(){closeModal();});
		}

		return false;
	});

	if(settings.open!==false && jQuery(modal).data("open")!==true){
		jQuery(this).triggerHandler('click.facebox');
	}

	return this.each(function() { 
	});
};

/*
	facebox Default Settings.
	
	The facebox() function takes one argument, an object of key/value pairs, that are used to initialize the modal.
	
	Please do not change these settings here, instead overwrite these settings when attaching the facebox() event to your anchors.
	Example (Global)	: jQuery.fn.facebox.settings.transition = "fade"; //changes the transition to fade for all facebox() events proceeding it's declaration.
	Example (Specific)	: jQuery("a[href='http://www.google.com']").facebox({fixedWidth:"90%", fixedHeight:"450px", iframe:true});
*/
jQuery.fn.facebox.settings = {
	transition : "elastic", // Transition types: "elastic", "fade", or "none".
	transitionSpeed : 500, // Sets the speed of the fade and elastic transitions, in milliseconds.
	initialWidth : "150", // Set the initial width of the modal, prior to any content being loaded.
	initialHeight : "150", // Set the initial height of the modal, prior to any content being loaded.
	fixedWidth : false, // Set a fixed width for div#loaded.  Example: "500px"
	fixedHeight : false, // Set a fixed height for div#modalLoadedContent.  Example: "500px"
	inline : false, // Set this to the selector of inline content to be displayed.  Example "#myHiddenDiv" or "body p".
	iframe : false, // If 'true' specifies that content should be displayed in an iFrame.
	href : false, // This can be used as an alternate anchor URL for facebox to use, or can be used to assign a URL for non-anchor elments such as images or form buttons.
	title : false, // This can be used as an alternate anchor title.
	bgOpacity : 0.65, // The modalBackgroundOverlay opacity level. Range: 0 to 1.
	preloading : true, // Allows for preloading of 'Next' and 'Previous' content in a shared relation group (same values for the 'rel' attribute), after the current content has finished loading.  Set to 'false' to disable.
	contentCurrent : "image {current} of {total}", // the format of the contentCurrent information
	contentPrevious : "previous", // the anchor text for the previous link in a shared relation group (same values for 'rel').
	contentNext : "next", // the anchor text for the next link in a shared relation group (same 'rel' attribute').
	modalClose : "close", // the anchor text for the close link.  Esc will also close the modal.
	open : false, //Automatically opens facebox. (fires the click.facebox event without waiting for user input).
	overlayClose : true,  //If true, enables closing facebox by clicking on the background overlay.
	scroll: false, // If true it will disable the scroll bar from the main window.
	form: false,
	action: false
};

})(jQuery);

var FaceBox = {

	initialize: function() {
	
	jQuery(".facebox").each(function(){

		var link = jQuery(this);
                link.removeAttr("onclick");
		var attr = "rel";
		var nodeName = this.nodeName;

		var metadata = {
			width: 800,
			height: 600,
			scroll: false,
			speed: 500,
			href: false,
			form: false,
			iframe: true,
			inline: false,
			action: false
		}

		var win = jQuery(window);
		var win_width = win.width();
		var win_height = win.height();

		if (nodeName === "INPUT" || nodeName === "BUTTON") {
			attr = "alt";
		}

		metadata = jQuery.extend({}, metadata, link.metadata({type: "attr", name: attr}));

		if (metadata.width > win_width) {
			metadata.width = win_width - 100
		}

		if (metadata.height > win_height) {
			metadata.height = win_height - 100
		}

		if (nodeName === "INPUT" || nodeName === "BUTTON") {
			metadata.iframe = false;
			metadata.form = link;
		}

		link.facebox({
			fixedWidth: metadata.width, 
			fixedHeight: metadata.height, 
			iframe: metadata.iframe, 
			inline: metadata.inline, 
			scroll: metadata.scroll, 
			transitionSpeed: metadata.speed, 
			href: metadata.href, 
			form: metadata.form,
			action: metadata.action
		});		

	});
	
	}

}

FaceBox.initialize();
/*
 * jQuery Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 2.6
 * Last Modified: 5/26/2009
 * 
 * Copyright 2009 Trent Richardson
 * Dual licensed under the MIT and GPL licenses.
 * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt
 * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt
 * 
 */
 
(function($) {
	$.prompt = function(message, options) {
		options = $.extend({},$.prompt.defaults,options);
		$.prompt.currentPrefix = options.prefix;

		var ie6		= ($.browser.msie && $.browser.version < 7);
		var $body	= $(document.body);
		var $window	= $(window);

		//build the box and fade
		var msgbox = '<div class="'+ options.prefix +'box" id="'+ options.prefix +'box">';
		if(options.useiframe && (($('object, applet').length > 0) || ie6)) {
			msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></iframe>';
		} else {
			if(ie6) {
				$('select').css('visibility','hidden');
			}
			msgbox +='<div class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></div>';
		}
		msgbox += '<div class="'+ options.prefix +'" id="'+ options.prefix +'"><div class="'+ options.prefix +'container"><div class="';
		msgbox += options.prefix +'close">X</div><div id="'+ options.prefix +'states"></div>';
		msgbox += '</div></div></div>';

		var $jqib	= $(msgbox).appendTo($body);
		var $jqi	= $jqib.children('#'+ options.prefix);
		var $jqif	= $jqib.children('#'+ options.prefix +'fade');

		//if a string was passed, convert to a single state
		if(message.constructor == String){
			message = {
				state0: {
					html: message,
				 	buttons: options.buttons,
				 	focus: options.focus,
				 	submit: options.submit
			 	}
		 	};
		}

		//build the states
		var states = "";

		$.each(message,function(statename,stateobj){
			stateobj = $.extend({},$.prompt.defaults.state,stateobj);
			message[statename] = stateobj;

			states += '<div id="'+ options.prefix +'_state_'+ statename +'" class="'+ options.prefix + '_state" style="display:none;"><div class="'+ options.prefix +'message">' + stateobj.html +'</div><div class="'+ options.prefix +'buttons">';
			$.each(stateobj.buttons, function(k, v){
				states += '<button name="' + options.prefix + '_' + statename + '_button' + k + '" id="' + options.prefix +	'_' + statename + '_button' + k + '" value="' + v + '">' + k + '</button>';
			});
			states += '</div></div>';
		});

		//insert the states...
		$jqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block');
		$jqi.find('.'+ options.prefix +'buttons:empty').css('display','none');
		
		//Events
		$.each(message,function(statename,stateobj){
			var $state = $jqi.find('#'+ options.prefix +'_state_'+ statename);

			$state.children('.'+ options.prefix +'buttons').children('button').click(function(){
				var msg = $state.children('.'+ options.prefix +'message');
				var clicked = stateobj.buttons[$(this).text()];
				var forminputs = {};

				//collect all form element values from all states
				$.each($jqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){
					if (forminputs[obj.name] === undefined) {
						forminputs[obj.name] = obj.value;
					} else if (typeof forminputs[obj.name] == Array) {
						forminputs[obj.name].push(obj.value);
					} else {
						forminputs[obj.name] = [forminputs[obj.name],obj.value];	
					} 
				});

				var close = stateobj.submit(clicked,msg,forminputs);
				if(close === undefined || close) {
					removePrompt(true,clicked,msg,forminputs);
				}
			});
			$state.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton');

		});

		var ie6scroll = function(){
			$jqib.css({ top: $window.scrollTop() });
		};

		var fadeClicked = function(){
			if(options.persistent){
				var i = 0;
				$jqib.addClass(options.prefix +'warning');
				var intervalid = setInterval(function(){
					$jqib.toggleClass(options.prefix +'warning');
					if(i++ > 1){
						clearInterval(intervalid);
						$jqib.removeClass(options.prefix +'warning');
					}
				}, 100);
			}
			else {
				removePrompt();
			}
		};
		
		var keyPressEventHandler = function(e){
			var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox?
			
			//escape key closes
			if(key==27) {
				removePrompt();	
			}
			
			//constrain tabs
			if (key == 9){
				var $inputels = $(':input:enabled:visible',$jqib);
				var fwd = !e.shiftKey && e.target == $inputels[$inputels.length-1];
				var back = e.shiftKey && e.target == $inputels[0];
				if (fwd || back) {
				setTimeout(function(){ 
					if (!$inputels)
						return;
					var el = $inputels[back===true ? $inputels.length-1 : 0];

					if (el)
						el.focus();						
				},10);
				return false;
				}
			}
		};
		
		var positionPrompt = function(){
			$jqib.css({
				position: (ie6) ? "absolute" : "fixed",
				height: $window.height(),
				width: "100%",
				top: (ie6)? $window.scrollTop() : 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jqif.css({
				position: "absolute",
				height: $window.height(),
				width: "100%",
				top: 0,
				left: 0,
				right: 0,
				bottom: 0
			});
			$jqi.css({
				position: "absolute",
				top: options.top,
				left: "50%",
				marginLeft: (($jqi.outerWidth()/2)*-1)
			});
		};

		var stylePrompt = function(){
			$jqif.css({
				zIndex: options.zIndex,
				display: "none",
				opacity: options.opacity
			});
			$jqi.css({
				zIndex: options.zIndex+1,
				display: "none"
			});
			$jqib.css({
				zIndex: options.zIndex
			});
		};

		var removePrompt = function(callCallback, clicked, msg, formvals){
			$jqi.remove();
			//ie6, remove the scroll event
			if(ie6) {
				$body.unbind('scroll',ie6scroll);
			}
			$window.unbind('resize',positionPrompt);
			$jqif.fadeOut(options.overlayspeed,function(){
				$jqif.unbind('click',fadeClicked);
				$jqif.remove();
				if(callCallback) {
					options.callback(clicked,msg,formvals);
				}
				$jqib.unbind('keypress',keyPressEventHandler);
				$jqib.remove();
				if(ie6 && !options.useiframe) {
					$('select').css('visibility','visible');
				}
			});
		};

		positionPrompt();
		stylePrompt();
		
		//ie6, add a scroll event to fix position:fixed
		if(ie6) {
			$window.scroll(ie6scroll);
		}
		$jqif.click(fadeClicked);
		$window.resize(positionPrompt);
		$jqib.bind("keydown keypress",keyPressEventHandler);
		$jqi.find('.'+ options.prefix +'close').click(removePrompt);

		//Show it
		$jqif.fadeIn(options.overlayspeed);
		$jqi[options.show](options.promptspeed,options.loaded);
		$jqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus();

		return $jqib;
	};
	
	$.prompt.defaults = {
		prefix:'jqi',
		buttons: {
			Ok: true
		},
	 	loaded: function(){

	 	},
	  	submit: function(){
	  		return true;
		},
	 	callback: function(){

	 	},
		opacity: 0.6,
	 	zIndex: 999,
	  	overlayspeed: 'slow',
	   	promptspeed: 'fast',
   		show: 'fadeIn',
	   	focus: 0,
	   	useiframe: false,
	 	top: "15%",
	  	persistent: true,
	  	state: {
			html: '',
		 	buttons: {
		 		Ok: true
		 	},
		  	focus: 0,
		   	submit: function(){
		   		return true;
		   }
	  	}
	};
	
	$.prompt.currentPrefix = $.prompt.defaults.prefix;

	$.prompt.setDefaults = function(o) {
		$.prompt.defaults = $.extend({}, $.prompt.defaults, o);
	};
	
	$.prompt.setStateDefaults = function(o) {
		$.prompt.defaults.state = $.extend({}, $.prompt.defaults.state, o);
	};
	
	$.prompt.getStateContent = function(state) {
		return $('#'+ $.prompt.currentPrefix +'_state_'+ state);
	};
	
	$.prompt.goToState = function(state) {
		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		$('#'+ $.prompt.currentPrefix +'_state_'+ state).slideDown('slow',function(){
			$(this).find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.nextState = function() {
		var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').next();

		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.prevState = function() {
		var $next = $('.'+ $.prompt.currentPrefix +'_state:visible').prev();

		$('.'+ $.prompt.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.prompt.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.prompt.close = function() {
		$('#'+ $.prompt.currentPrefix +'box').fadeOut('fast',function(){
        		$(this).remove();
		});
	};
	
})(jQuery);

jQuery(document).ready(function() {
  jQuery('a.event').click(function() {
    jQuery.prompt(
      jQuery(this).parent('p').siblings('.event-type-container:hidden').html(),
      {
        opacity: 0.3, 
        prefix: "financial-diary-popup",
        Ok: true,
        Cancel: false
      }
    );
    return false;
  });
});
jQuery(document).ready(function() {
  // set the initial default text in the investment input box
  jQuery("#investment").val("By investment name");
  
  // change the text to black and clear the default text
  jQuery("#investment").focus(function() {
    jQuery(this).removeClass("default-input-text");
    jQuery(this).addClass("non-default-input-text");
    if(jQuery(this).val() == "By investment name")
    {
      jQuery(this).val("");
    }
  });
  
  // change the text back to grey and put the default back in if nothing has been entered
  jQuery("#investment").blur(function() {
    jQuery(this).removeClass("non-default-input-text");
    jQuery(this).addClass("default-input-text");
    if(jQuery(this).val() == "")
    {
      jQuery(this).val("By investment name");
    }
  });
  
  // add a submit handler that clears the value of the investment input box if not used
  jQuery("#fund-search-home").submit(function() {
    if(jQuery("#investment").val() == "By investment name" || jQuery("#investment").val() == "")
    {
      jQuery("#investment").attr('disabled', true);
    }
    
    return true;
  });
    
  // populate the select boxes when the page loads since Matrix can't do it
  var companyid = getUrlParam("companyid");
  var sectorid = getUrlParam("sectorid");
  
  if(companyid != "")
  {
    jQuery("#companyid").val(companyid);
  }
  
  if(sectorid != "")
  {
    jQuery("#sectorid").val(sectorid);
  }
  
  // if either select box is changed, reset the other
  jQuery("#companyid").change(function() {
    if(jQuery(this).parents(".wealth150").length == 0) {
      jQuery("#sectorid option[value='']").attr("selected", "selected");
    }
  });

  jQuery("#sectorid").change(function() {
    if(jQuery(this).parents(".wealth150").length == 0) {
      jQuery("#companyid option[value='']").attr("selected", "selected");
    }
  });
});


function getUrlParam(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
  {
    return "";
  }
  else
  {
    return results[1];
  }
}
var total = parseInt(jQuery("#latest-ideas-count").html());
var current_idea = 0;
var timer = null;

jQuery(document).ready(function() {
  scrollideas(1);
});

function scrollideas(dir)
{	
  if(total < 1)
  {
    jQuery("#idea0").html("Latest investment ideas are not available at present.");
    return;
  }

  jQuery("[id^='idea']").hide();
  jQuery("#idea-previous-next").show();

  var next_id = current_idea + dir;

  if(dir == 1 && next_id > total)
  {
    next_id = 1;
  }
  else if(dir == -1 && next_id < 1)
  {
    next_id = total;
  }
  
  if(jQuery("#idea" + next_id).length > 0)
  {
    jQuery("#idea" + next_id).show();
  }

  current_idea = next_id;

  if(jQuery("#idea-count").length > 0)
  {
    jQuery("#idea-count").html(current_idea + " of " + total);
  }

  clearTimeout(timer);
  timer = setTimeout('scrollideas(1)', 7000);
}
/*

highlight v3

Highlights arbitrary terms.

<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>

MIT license.

Johann Burkard
<http://johannburkard.de>
<mailto:jb@eaio.com>

*/

jQuery.fn.highlight = function(pat) {
 function innerHighlight(node, pat) {
  var skip = 0;
  if (node.nodeType == 3) {
   var pos = node.data.toUpperCase().indexOf(pat);
   if (pos >= 0) {
    var spannode = document.createElement('span');
    spannode.className = 'highlight';
    var middlebit = node.splitText(pos);
    var endbit = middlebit.splitText(pat.length);
    var middleclone = middlebit.cloneNode(true);
    spannode.appendChild(middleclone);
    middlebit.parentNode.replaceChild(spannode, middlebit);
    skip = 1;
   }
  }
  else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
   for (var i = 0; i < node.childNodes.length; ++i) {
    i += innerHighlight(node.childNodes[i], pat);
   }
  }
  return skip;
 }
 return this.each(function() {
  innerHighlight(this, pat.toUpperCase());
 });
};

jQuery.fn.removeHighlight = function() {
 return this.find("span.highlight").each(function() {
  this.parentNode.firstChild.nodeName;
  with (this.parentNode) {
   replaceChild(this.firstChild, this);
   normalize();
  }
 }).end();
};
var EPIC_Search = {

	container: jQuery("#epic-search-results-conatiner"),
	links: jQuery(".epic-result"),
	
	initialize: function() {
	
		var self = EPIC_Search;
	
		if (!self.container.length) {
			return false;
		}
		
		if (self.links.length == 1) {
			window.location = self.links[0].href;
		}
	
	}

}

//EPIC_Search.initialize();

var Search_Highlight = {

	container: jQuery("#content .search-results"),
	keyword: jQuery("#query").val(),
	
	initialize: function() {

		var self = Search_Highlight;

		if (!self.container.length) {
			return false;
		}

		self.container.highlight(self.keyword.toUpperCase());

	}

}

jQuery(document).ready(function() {
	Search_Highlight.initialize();
});
/*
 * jQuery validation plug-in 1.5.2
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-validation/
 * http://docs.jquery.com/Plugins/Validation
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6243 2009-02-19 11:40:49Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){$.extend($.fn,{validate:function(options){if(!this.length){options&&options.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing");return;}var validator=$.data(this[0],'validator');if(validator){return validator;}validator=new $.validator(options,this[0]);$.data(this[0],'validator',validator);if(validator.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){validator.cancelSubmit=true;});this.submit(function(event){if(validator.settings.debug)event.preventDefault();function handle(){if(validator.settings.submitHandler){validator.settings.submitHandler.call(validator,validator.currentForm);return false;}return true;}if(validator.cancelSubmit){validator.cancelSubmit=false;return handle();}if(validator.form()){if(validator.pendingRequest){validator.formSubmitted=true;return false;}return handle();}else{validator.focusInvalid();return false;}});}return validator;},valid:function(){if($(this[0]).is('form')){return this.validate().form();}else{var valid=false;var validator=$(this[0].form).validate();this.each(function(){valid|=validator.element(this);});return valid;}},removeAttrs:function(attributes){var result={},$element=this;$.each(attributes.split(/\s/),function(index,value){result[value]=$element.attr(value);$element.removeAttr(value);});return result;},rules:function(command,argument){var element=this[0];if(command){var settings=$.data(element.form,'validator').settings;var staticRules=settings.rules;var existingRules=$.validator.staticRules(element);switch(command){case"add":$.extend(existingRules,$.validator.normalizeRule(argument));staticRules[element.name]=existingRules;if(argument.messages)settings.messages[element.name]=$.extend(settings.messages[element.name],argument.messages);break;case"remove":if(!argument){delete staticRules[element.name];return existingRules;}var filtered={};$.each(argument.split(/\s/),function(index,method){filtered[method]=existingRules[method];delete existingRules[method];});return filtered;}}var data=$.validator.normalizeRules($.extend({},$.validator.metadataRules(element),$.validator.classRules(element),$.validator.attributeRules(element),$.validator.staticRules(element)),element);if(data.required){var param=data.required;delete data.required;data=$.extend({required:param},data);}return data;}});$.extend($.expr[":"],{blank:function(a){return!$.trim(a.value);},filled:function(a){return!!$.trim(a.value);},unchecked:function(a){return!a.checked;}});$.format=function(source,params){if(arguments.length==1)return function(){var args=$.makeArray(arguments);args.unshift(source);return $.format.apply(this,args);};if(arguments.length>2&&params.constructor!=Array){params=$.makeArray(arguments).slice(1);}if(params.constructor!=Array){params=[params];}$.each(params,function(i,n){source=source.replace(new RegExp("\\{"+i+"\\}","g"),n);});return source;};$.validator=function(options,form){this.settings=$.extend({},$.validator.defaults,options);this.currentForm=form;this.init();};$.extend($.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",errorElement:"label",focusInvalid:true,errorContainer:$([]),errorLabelContainer:$([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(element){this.lastActive=element;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,element,this.settings.errorClass);this.errorsFor(element).hide();}},onfocusout:function(element){if(!this.checkable(element)&&(element.name in this.submitted||!this.optional(element))){this.element(element);}},onkeyup:function(element){if(element.name in this.submitted||element==this.lastElement){this.element(element);}},onclick:function(element){if(element.name in this.submitted)this.element(element);},highlight:function(element,errorClass){$(element).addClass(errorClass);},unhighlight:function(element,errorClass){$(element).removeClass(errorClass);}},setDefaults:function(settings){$.extend($.validator.defaults,settings);},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",dateDE:"Bitte geben Sie ein gültiges Datum ein.",number:"Please enter a valid number.",numberDE:"Bitte geben Sie eine Nummer ein.",digits:"Please enter only digits",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",accept:"Please enter a value with a valid extension.",maxlength:$.format("Please enter no more than {0} characters."),minlength:$.format("Please enter at least {0} characters."),rangelength:$.format("Please enter a value between {0} and {1} characters long."),range:$.format("Please enter a value between {0} and {1}."),max:$.format("Please enter a value less than or equal to {0}."),min:$.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){this.labelContainer=$(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||$(this.currentForm);this.containers=$(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var groups=(this.groups={});$.each(this.settings.groups,function(key,value){$.each(value.split(/\s/),function(index,name){groups[name]=key;});});var rules=this.settings.rules;$.each(rules,function(key,value){rules[key]=$.validator.normalizeRule(value);});function delegate(event){var validator=$.data(this[0].form,"validator");validator.settings["on"+event.type]&&validator.settings["on"+event.type].call(validator,this[0]);}$(this.currentForm).delegate("focusin focusout keyup",":text, :password, :file, select, textarea",delegate).delegate("click",":radio, :checkbox",delegate);if(this.settings.invalidHandler)$(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler);},form:function(){this.checkForm();$.extend(this.submitted,this.errorMap);this.invalid=$.extend({},this.errorMap);if(!this.valid())$(this.currentForm).triggerHandler("invalid-form",[this]);this.showErrors();return this.valid();},checkForm:function(){this.prepareForm();for(var i=0,elements=(this.currentElements=this.elements());elements[i];i++){this.check(elements[i]);}return this.valid();},element:function(element){element=this.clean(element);this.lastElement=element;this.prepareElement(element);this.currentElements=$(element);var result=this.check(element);if(result){delete this.invalid[element.name];}else{this.invalid[element.name]=true;}if(!this.numberOfInvalids()){this.toHide=this.toHide.add(this.containers);}this.showErrors();return result;},showErrors:function(errors){if(errors){$.extend(this.errorMap,errors);this.errorList=[];for(var name in errors){this.errorList.push({message:errors[name],element:this.findByName(name)[0]});}this.successList=$.grep(this.successList,function(element){return!(element.name in errors);});}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors();},resetForm:function(){if($.fn.resetForm)$(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass);},numberOfInvalids:function(){return this.objectLength(this.invalid);},objectLength:function(obj){var count=0;for(var i in obj)count++;return count;},hideErrors:function(){this.addWrapper(this.toHide).hide();},valid:function(){return this.size()==0;},size:function(){return this.errorList.length;},focusInvalid:function(){if(this.settings.focusInvalid){try{$(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus();}catch(e){}}},findLastActive:function(){var lastActive=this.lastActive;return lastActive&&$.grep(this.errorList,function(n){return n.element.name==lastActive.name;}).length==1&&lastActive;},elements:function(){var validator=this,rulesCache={};return $([]).add(this.currentForm.elements).filter(":input").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&validator.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in rulesCache||!validator.objectLength($(this).rules()))return false;rulesCache[this.name]=true;return true;});},clean:function(selector){return $(selector)[0];},errors:function(){return $(this.settings.errorElement+"."+this.settings.errorClass,this.errorContext);},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=$([]);this.toHide=$([]);this.formSubmitted=false;this.currentElements=$([]);},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers);},prepareElement:function(element){this.reset();this.toHide=this.errorsFor(element);},check:function(element){element=this.clean(element);if(this.checkable(element)){element=this.findByName(element.name)[0];}var rules=$(element).rules();var dependencyMismatch=false;for(method in rules){var rule={method:method,parameters:rules[method]};try{var result=$.validator.methods[method].call(this,element.value.replace(/\r/g,""),element,rule.parameters);if(result=="dependency-mismatch"){dependencyMismatch=true;continue;}dependencyMismatch=false;if(result=="pending"){this.toHide=this.toHide.not(this.errorsFor(element));return;}if(!result){this.formatAndAdd(element,rule);return false;}}catch(e){this.settings.debug&&window.console&&console.log("exception occured when checking element "+element.id
+", check the '"+rule.method+"' method");throw e;}}if(dependencyMismatch)return;if(this.objectLength(rules))this.successList.push(element);return true;},customMetaMessage:function(element,method){if(!$.metadata)return;var meta=this.settings.meta?$(element).metadata()[this.settings.meta]:$(element).metadata();return meta&&meta.messages&&meta.messages[method];},customMessage:function(name,method){var m=this.settings.messages[name];return m&&(m.constructor==String?m:m[method]);},findDefined:function(){for(var i=0;i<arguments.length;i++){if(arguments[i]!==undefined)return arguments[i];}return undefined;},defaultMessage:function(element,method){return this.findDefined(this.customMessage(element.name,method),this.customMetaMessage(element,method),!this.settings.ignoreTitle&&element.title||undefined,$.validator.messages[method],"<strong>Warning: No message defined for "+element.name+"</strong>");},formatAndAdd:function(element,rule){var message=this.defaultMessage(element,rule.method);if(typeof message=="function")message=message.call(this,rule.parameters,element);this.errorList.push({message:message,element:element});this.errorMap[element.name]=message;this.submitted[element.name]=message;},addWrapper:function(toToggle){if(this.settings.wrapper)toToggle=toToggle.add(toToggle.parents(this.settings.wrapper));return toToggle;},defaultShowErrors:function(){for(var i=0;this.errorList[i];i++){var error=this.errorList[i];this.settings.highlight&&this.settings.highlight.call(this,error.element,this.settings.errorClass);this.showLabel(error.element,error.message);}if(this.errorList.length){this.toShow=this.toShow.add(this.containers);}if(this.settings.success){for(var i=0;this.successList[i];i++){this.showLabel(this.successList[i]);}}if(this.settings.unhighlight){for(var i=0,elements=this.validElements();elements[i];i++){this.settings.unhighlight.call(this,elements[i],this.settings.errorClass);}}this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show();},validElements:function(){return this.currentElements.not(this.invalidElements());},invalidElements:function(){return $(this.errorList).map(function(){return this.element;});},showLabel:function(element,message){var label=this.errorsFor(element);if(label.length){label.removeClass().addClass(this.settings.errorClass);label.attr("generated")&&label.html(message);}else{label=$("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(element),generated:true}).addClass(this.settings.errorClass).html(message||"");if(this.settings.wrapper){label=label.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();}if(!this.labelContainer.append(label).length)this.settings.errorPlacement?this.settings.errorPlacement(label,$(element)):label.insertAfter(element);}if(!message&&this.settings.success){label.text("");typeof this.settings.success=="string"?label.addClass(this.settings.success):this.settings.success(label);}this.toShow=this.toShow.add(label);},errorsFor:function(element){return this.errors().filter("[for='"+this.idOrName(element)+"']");},idOrName:function(element){return this.groups[element.name]||(this.checkable(element)?element.name:element.id||element.name);},checkable:function(element){return/radio|checkbox/i.test(element.type);},findByName:function(name){var form=this.currentForm;return $(document.getElementsByName(name)).map(function(index,element){return element.form==form&&element.name==name&&element||null;});},getLength:function(value,element){switch(element.nodeName.toLowerCase()){case'select':return $("option:selected",element).length;case'input':if(this.checkable(element))return this.findByName(element.name).filter(':checked').length;}return value.length;},depend:function(param,element){return this.dependTypes[typeof param]?this.dependTypes[typeof param](param,element):true;},dependTypes:{"boolean":function(param,element){return param;},"string":function(param,element){return!!$(param,element.form).length;},"function":function(param,element){return param(element);}},optional:function(element){return!$.validator.methods.required.call(this,$.trim(element.value),element)&&"dependency-mismatch";},startRequest:function(element){if(!this.pending[element.name]){this.pendingRequest++;this.pending[element.name]=true;}},stopRequest:function(element,valid){this.pendingRequest--;if(this.pendingRequest<0)this.pendingRequest=0;delete this.pending[element.name];if(valid&&this.pendingRequest==0&&this.formSubmitted&&this.form()){$(this.currentForm).submit();}else if(!valid&&this.pendingRequest==0&&this.formSubmitted){$(this.currentForm).triggerHandler("invalid-form",[this]);}},previousValue:function(element){return $.data(element,"previousValue")||$.data(element,"previousValue",previous={old:null,valid:true,message:this.defaultMessage(element,"remote")});}},classRuleSettings:{required:{required:true},email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(className,rules){className.constructor==String?this.classRuleSettings[className]=rules:$.extend(this.classRuleSettings,className);},classRules:function(element){var rules={};var classes=$(element).attr('class');classes&&$.each(classes.split(' '),function(){if(this in $.validator.classRuleSettings){$.extend(rules,$.validator.classRuleSettings[this]);}});return rules;},attributeRules:function(element){var rules={};var $element=$(element);for(method in $.validator.methods){var value=$element.attr(method);if(value){rules[method]=value;}}if(rules.maxlength&&/-1|2147483647|524288/.test(rules.maxlength)){delete rules.maxlength;}return rules;},metadataRules:function(element){if(!$.metadata)return{};var meta=$.data(element.form,'validator').settings.meta;return meta?$(element).metadata()[meta]:$(element).metadata();},staticRules:function(element){var rules={};var validator=$.data(element.form,'validator');if(validator.settings.rules){rules=$.validator.normalizeRule(validator.settings.rules[element.name])||{};}return rules;},normalizeRules:function(rules,element){$.each(rules,function(prop,val){if(val===false){delete rules[prop];return;}if(val.param||val.depends){var keepRule=true;switch(typeof val.depends){case"string":keepRule=!!$(val.depends,element.form).length;break;case"function":keepRule=val.depends.call(element,element);break;}if(keepRule){rules[prop]=val.param!==undefined?val.param:true;}else{delete rules[prop];}}});$.each(rules,function(rule,parameter){rules[rule]=$.isFunction(parameter)?parameter(element):parameter;});$.each(['minlength','maxlength','min','max'],function(){if(rules[this]){rules[this]=Number(rules[this]);}});$.each(['rangelength','range'],function(){if(rules[this]){rules[this]=[Number(rules[this][0]),Number(rules[this][1])];}});if($.validator.autoCreateRanges){if(rules.min&&rules.max){rules.range=[rules.min,rules.max];delete rules.min;delete rules.max;}if(rules.minlength&&rules.maxlength){rules.rangelength=[rules.minlength,rules.maxlength];delete rules.minlength;delete rules.maxlength;}}if(rules.messages){delete rules.messages}return rules;},normalizeRule:function(data){if(typeof data=="string"){var transformed={};$.each(data.split(/\s/),function(){transformed[this]=true;});data=transformed;}return data;},addMethod:function(name,method,message){$.validator.methods[name]=method;$.validator.messages[name]=message;if(method.length<3){$.validator.addClassRules(name,$.validator.normalizeRule(name));}},methods:{required:function(value,element,param){if(!this.depend(param,element))return"dependency-mismatch";switch(element.nodeName.toLowerCase()){case'select':var options=$("option:selected",element);return options.length>0&&(element.type=="select-multiple"||($.browser.msie&&!(options[0].attributes['value'].specified)?options[0].text:options[0].value).length>0);case'input':if(this.checkable(element))return this.getLength(value,element)>0;default:return $.trim(value).length>0;}},remote:function(value,element,param){if(this.optional(element))return"dependency-mismatch";var previous=this.previousValue(element);if(!this.settings.messages[element.name])this.settings.messages[element.name]={};this.settings.messages[element.name].remote=typeof previous.message=="function"?previous.message(value):previous.message;param=typeof param=="string"&&{url:param}||param;if(previous.old!==value){previous.old=value;var validator=this;this.startRequest(element);var data={};data[element.name]=value;$.ajax($.extend(true,{url:param,mode:"abort",port:"validate"+element.name,dataType:"json",data:data,success:function(response){if(response){var submitted=validator.formSubmitted;validator.prepareElement(element);validator.formSubmitted=submitted;validator.successList.push(element);validator.showErrors();}else{var errors={};errors[element.name]=response||validator.defaultMessage(element,"remote");validator.showErrors(errors);}previous.valid=response;validator.stopRequest(element,response);}},param));return"pending";}else if(this.pending[element.name]){return"pending";}return previous.valid;},minlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)>=param;},maxlength:function(value,element,param){return this.optional(element)||this.getLength($.trim(value),element)<=param;},rangelength:function(value,element,param){var length=this.getLength($.trim(value),element);return this.optional(element)||(length>=param[0]&&length<=param[1]);},min:function(value,element,param){return this.optional(element)||value>=param;},max:function(value,element,param){return this.optional(element)||value<=param;},range:function(value,element,param){return this.optional(element)||(value>=param[0]&&value<=param[1]);},email:function(value,element){return this.optional(element)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);},url:function(value,element){return this.optional(element)||/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);},date:function(value,element){return this.optional(element)||!/Invalid|NaN/.test(new Date(value));},dateISO:function(value,element){return this.optional(element)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(value);},dateDE:function(value,element){return this.optional(element)||/^\d\d?\.\d\d?\.\d\d\d?\d?$/.test(value);},number:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);},numberDE:function(value,element){return this.optional(element)||/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);},digits:function(value,element){return this.optional(element)||/^\d+$/.test(value);},creditcard:function(value,element){if(this.optional(element))return"dependency-mismatch";if(/[^0-9-]+/.test(value))return false;var nCheck=0,nDigit=0,bEven=false;value=value.replace(/\D/g,"");for(n=value.length-1;n>=0;n--){var cDigit=value.charAt(n);var nDigit=parseInt(cDigit,10);if(bEven){if((nDigit*=2)>9)nDigit-=9;}nCheck+=nDigit;bEven=!bEven;}return(nCheck%10)==0;},accept:function(value,element,param){param=typeof param=="string"?param:"png|jpe?g|gif";return this.optional(element)||value.match(new RegExp(".("+param+")$","i"));},equalTo:function(value,element,param){return value==$(param).val();}}});})(jQuery);;(function($){var ajax=$.ajax;var pendingRequests={};$.ajax=function(settings){settings=$.extend(settings,$.extend({},$.ajaxSettings,settings));var port=settings.port;if(settings.mode=="abort"){if(pendingRequests[port]){pendingRequests[port].abort();}return(pendingRequests[port]=ajax.apply(this,arguments));}return ajax.apply(this,arguments);};})(jQuery);;(function($){$.each({focus:'focusin',blur:'focusout'},function(original,fix){$.event.special[fix]={setup:function(){if($.browser.msie)return false;this.addEventListener(original,$.event.special[fix].handler,true);},teardown:function(){if($.browser.msie)return false;this.removeEventListener(original,$.event.special[fix].handler,true);},handler:function(e){arguments[0]=$.event.fix(e);arguments[0].type=fix;return $.event.handle.apply(this,arguments);}};});$.extend($.fn,{delegate:function(type,delegate,handler){return this.bind(type,function(event){var target=$(event.target);if(target.is(delegate)){return handler.apply(target,arguments);}});},triggerEvent:function(type,target){return this.triggerHandler(type,[$.event.fix({type:type,target:target})]);}})})(jQuery);
