/*
*  global.js
*  Copyright 2010, Hoop Associates Ltd
*  Hoop Associates	www.thisishoop.com	mail@hoopassociates.co.uk
*/

(function($){

	$.fn.toggleField = function(){
		return this.each(function(){
			var $field = 
			$(this)
			.data('val', $(this).val())
			.focus(function(){
				this.value = ($.trim(this.value) == $field.data('val') ? '' : this.value);
			})
			.blur(function(){
				this.value = ($.trim(this.value) == '' ? $field.data('val') : this.value);
			});
		});
	};
	
	$.fn.toggleNav = function(options){
		return this.each(function(){

			options = $.extend({
				speed: 200,
				cssClass: 'toggle'
			}, options || {});

			$(this).find("ul li").each(function(){
                        if (!$("ul:first", this).length || !$("ul:first", this).children().length) return true;
				var self = this;

				$('<span />')
				.addClass(options.cssClass)
				.html($("ul:first", this).is(":visible") ? '-' : '+')
				.click(function(){
					var span = this;
					$("ul:first", self).animate({
						height: 'toggle',
						opacity: 'toggle'
					}, ($.isIE6 ? 0 : options.speed), function(){
						$(span).html($(this).is(':visible') ? '-' : '+');
					});
					return false;
				})
				.appendTo($(this).find("a:first"));
			});
		});
	};

	$.fn.textsize = function(){
		return this.each(function(){
			$(this)
			.find('.medium')
			.click(function(){
				$('body').css({fontSize: '62.5%'});
                                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
				$.cookie('resizecookie', '62.5%'); //sets to 62.5%

			}).end()
			.find('.large')
			.click(function(){
				$('body').css({fontSize: '70%'});
                                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
				$.cookie('resizecookie', '70%'); //sets to 70%
			}).end()
			.find('.largest')
			.click(function(){
				$('body').css({fontSize: '80%'});
                                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
				$.cookie('resizecookie', '80%'); //sets to 80%
			});
		});
	};

        $.fn.textVersion = function(){
        return this.each(function(){
            $(this)
            .find('.textonly-button')
            .click(function(){
             //alert("hi in text only");
              if($('#main_css').attr('href') == 'http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css'){
                 //alert(' css is empty');
                $('#main_css').attr('href','http://www.ombudsman.org.uk/_designs/css/main_min.css');
                $('#framework_css').attr('href','');
                //$('.langlink').removeAttr('style');
                 $('.helplink').removeAttr("style");
                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
                $.cookie('access_cookie', 'http://www.ombudsman.org.uk/_designs/css/main_min.css', { path: "/" }); //sets to off
                 //alert("cookie = " + $.cookie('access_cookie'));
              }
               else if($('#main_css').attr('href') ==  'http://www.ombudsman.org.uk/__data/assets/css_file/0020/5276/contrastwithbg.css'){
                 //alert(' css is contrast css');
               // $('#main_css').attr('href','');
                //$('#framework_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0015/2049/framework.css'); 

                 $('#main_css').attr('href','http://www.ombudsman.org.uk/_designs/css/main_min.css'); 
                 $('#framework_css').attr('href','');             
                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
                $.cookie('access_cookie', 'http://www.ombudsman.org.uk/_designs/css/main_min.css', { path: "/" }); //sets to off
                 //alert("cookie = " + $.cookie('access_cookie'));
              }

              else{
               //alert("cookie text not empty");
               //alert(' css is main css');
                //alert("cookie = " + $.cookie('access_cookie'));
                $('#main_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css');
                $('#framework_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0015/2049/framework.css');           
                $.cookie('access_cookie', 'http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css', { path: "/" }); //sets value of href
                //alert("cookie = " + $.cookie('access_cookie'));
              }
            }).end()
        });
       };

        $.fn.contrastVersion = function(){
        return this.each(function(){
            $(this)
            .find('.contrast-button')
            .click(function(){
            //alert("hi in contrastonly");
              if($('#main_css').attr('href') == 'http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css' || $('#main_css').attr('href') == 'http://www.ombudsman.org.uk/_designs/css/main_min.css' ){
                //alert('contrast only - css = main or empty');
                $('#main_css').attr('href','http://www.ombudsman.org.uk/__data/assets/css_file/0020/5276/contrastwithbg.css');
 $('#framework_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0015/2049/framework.css');  
                              
                $.cookie('access_cookie', 'http://www.ombudsman.org.uk/__data/assets/css_file/0020/5276/contrastwithbg.css', { path: "/" }); 
                //alert("cookie = " + $.cookie('access_cookie'));
                }
              else{
                //alert('contrast only - css = contrast version');
                $('#main_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css');
                $('#framework_css').attr('href','http://www.ombudsman.org.uk/__data/assets/file/0015/2049/framework.css');   
                $.cookie('access_cookie', 'http://www.ombudsman.org.uk/__data/assets/file/0003/1884/main.css', { path: "/" }); //sets to off
                 //alert("cookie = " + $.cookie('access_cookie'));
              }
            }).end()     
        });
       };


	$.fn.complaintsFilter = function(options, callback){
		return this.each(function(){
			(!$(this).data('complaints-filter')) && 
				$(this).data('complaints-filter', new $.ComplaintsFilter(this, options, callback));
		});
	};


	$.ComplaintsFilter = function(obj, options, callback){

		this.$obj = $(obj).addClass('complaints-filter');

		this.options = $.extend({
			processData: window.$.pdata || {},
			startId: 0,			// start node of process data
			assetUrl: 'http://www.ombudsman.org.uk/system-calls/geturl',	// URL string to retrieve target URL from asset_id
			show: false,			// show the first dropdown on build?
			showButton: false,		// button selector - to show dropdow container
			animate: true,			// make fancy?
			animateSpeed: 220,		// how fancy?
			targetAutoload: false,		// load target URL on select change?
			targetButton: false,		// button selector - to load target URL
			ie6Mode: false,			// force ie6 mode, (used for debugging)
			showTooltips: true,		// show tooltips?
			tooltipConfig: {
				delay: 100,		// intentional hover
				position: 'right'	// position of tooltip
			},
			selectmenuConfig: {		// passed to the ui.selectmenu widget
				style: 'dropdown',	
				maxHeight: 220,
				transferClasses: true
			}
		}, options || {});
		this.options.fancyDropdowns = (!$.isIE6 && !this.options.ie6Mode && !$.isMobile);
		//this.options.fancyDropdowns = false

		this.elements = {
			$nojavascript: this.$obj.find('.complaints-nojavascript'),
			$summary: this.$obj.find('.complaints-summary'),
			$dropdowns: this.$obj.find('.complaints-dropdowns').length ? this.$obj.find('.complaints-dropdowns').show() : $('<div/>').addClass('complaints-dropdowns').appendTo(this.$obj),
			$targetButtons: this.$obj.find('.complaints-target-buttons').remove(),
			$buttonView: this.options.targetButton || this.$obj.find('.button-view'),
			dropdowns : []
		};
		this._init();
	};

	$.ComplaintsFilter.prototype = {

		_init : function(){
			this.elements.$nojavascript.hide();
			this.elements.$summary.show();
			this.data = { asset_id: 0 };
			this._cacheImages();
			this._bindEvents();

			if (this.options.show) {
				this._show(false);
			}
		},

		_cacheImages : function(){
			$.each([], function() {
				new Image().src = this;
			});
		},
		
		_bindEvents : function(){

			var self = this, resizeTimer = null;
			
			// bind select menu events
			this.options.selectmenuConfig = $.extend(this.options.selectmenuConfig, {
				change: function(e, ui) {
					self.dropdowns.events._change.call(self, e, ui);
				},
				open: function(e, ui) {
					self.dropdowns.events._open.call(self, e, ui);
				},
				close: function(e, ui) {
					self.dropdowns.events._close.call(self, e, ui);
				}
			});

			// show/hide dropdowns on view button click		
			this.elements.$buttonView.click(function(e){
				e.preventDefault();
				self._show();
			});
			
			// rebuild drodowns on window resize
			$(window).bind('resize', function() {

				// hide the select menus to prevent layout weirdness
				$('.ui-selectmenu-menu').hide();

				// prevent excessive rebuilds
				(resizeTimer) && clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function(){
					self.dropdowns._resize.call(self);
				}, 120);
			});
		},

		_show: function(){
			if (!this.elements.$dropdowns.height()) {
				// build the first dropdown in the set
				this.dropdowns._build.call(this, this.options.startId);
				this.elements.$buttonView.find('.bg-east').html('<span class="icon-collapse">&nbsp;</span>Hide');
			} else {
				// hide and reset the dropdowns
				this.dropdowns._reset.call(this);
				this.elements.$buttonView.find('.bg-east').html('<span class="icon">&nbsp;</span>View');
			}
		},

		dropdowns : {

			_buildSelect : function(data){
				var self = this, start = (new Date).getTime();

				// use the first option for the select label title
				$('<option/>').text(data.title).appendTo(self.elements.$select);
	
				// build the option string	
				var i = 0, options = [], length = data.options.length;
				while(i < length) {
					options.push('<option id="' + data.id + '.' + data.options[i].id + '" rel="'+(data.options[i].asset_id || 0)+'">'+data.options[i].text+'</option>');
					i++;
				}
				// append the options string to the select element
				self.elements.$select.append(options.join(''));

				// get the width of the select container
				var containerWidth = self.elements.$selectContainer.outerWidth();

				// now we can insert into the dom
				self.elements.$selectContainer.prepend(self.elements.$select);
				
				var diff = (new Date).getTime() - start;

				(window.console) && console.log('Dropdown build: ' + diff + ' milliseconds');
				
				// store the dropdown for later use
				self.elements.dropdowns.push(self.elements.$select);

				if (self.options.fancyDropdowns) {
					// build the selectmenu
					self.elements.$select.selectmenu(self.options.selectmenuConfig);
				} else {
					// don't build the selectmenu and bind the change event to select
					self.elements.$select.change(function(event){
						self.dropdowns.events._change.call(self, event); 
					});
					// adjust the width of the select
					var tooltipIconWidth = self.elements.$select.next().outerWidth(), selectWidth = (containerWidth - tooltipIconWidth - 12);
					self.elements.$select.width(selectWidth);
				}
			},

			_build : function(dropdownId){

				dropdownId = dropdownId || this.options.startId;

				var self = this, data = this.options.processData.get(dropdownId) || alert('Unable to retrieve the process data for: ' + dropdownId);

				// build the select container
				this.elements.$selectContainer = 
				$('<div/>', {
					className: 'complaints-select-container clearfix'
				}).appendTo(this.elements.$dropdowns);

				// build the dropdown anchor (this is done before the dropdown build to prevent obvious delays in building super-massive dropdowns)
				if (this.options.fancyDropdowns) {
					var ids = [ 'cf_select_' + dropdownId + '-' + 'button', dropdownId + '-' + 'menu' ];
					this.elements.$selectAnchor = $('<a class="ui-selectmenu ui-widget ui-state-default ui-corner-all" id="'+ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+ids[1]+'" />').appendTo(this.elements.$selectContainer);
					this.elements.$selectmenuIcon = $('<span class="ui-selectmenu-icon ui-icon ui-icon-triangle-1-s"></span>').prependTo(this.elements.$selectAnchor)
					this.elements.$selectmenuOverlay = $('<span class="ui-selectmenu-ellipsis-overlay"></span>').prependTo(this.elements.$selectAnchor);
					this.elements.$selectAnchor.prepend('<span class="ui-selectmenu-bg-west"><span class="ui-selectmenu-bg-east"><span class="ui-selectmenu-status">'+data.title+'</span></span></span>');
				}
				
				// build the select element (don't insert into DOM yet, rely on the documentFragment being faster)
				self.elements.$select = $('<select/>', {
					id: 'cf_select_' + dropdownId,
					name: dropdownId
				}).data('data_id', data.id);
				
				// build the tooltips
				if (self.options.showTooltips && data.tooltip) {
					if (data.tooltip) {
						self.elements.$select
						.data('tooltip', 
							$('<a/>', {
								title: data.tooltip,
								className: 'tooltip'
							})
							.html('&nbsp;')
							.tooltip(self.options.tooltipConfig)
							.appendTo(self.elements.$selectContainer)
						);
					}
					self.elements.$select.addClass('ui-selectmenu-tooltip-adjust');
					if (self.options.fancyDropdowns) {
						self.elements.$selectAnchor.addClass('ui-selectmenu-tooltip-adjust');
					}
				}

				if (!this.options.fancyDropdowns) {
					self.dropdowns._buildSelect.call(self, data);
					self.dropdowns._show.call(self, self.elements.$select, null, self.options.animateSpeed, function(){
						($.browser.msie) && this.style.removeAttribute('filter');
					});
				} else {
					// show the selectmenu anchor before building the selectmenu
					this.dropdowns._show.call(this, this.elements.$select, function(){
						($.browser.msie) && this.style.removeAttribute('filter');
						// give the brower time to catchup after the animations
						setTimeout(function(){
							self.dropdowns._buildSelect.call(self, data);
						});
					}, self.options.animateSpeed);
				}
			},

			_buildEllipsis: function(selects){

				var self = this;

				$.each(selects, function(){

					var $select = $(this), $ellipsis = $select.next().find('.ui-selectmenu-ellipsis');
					
					if ($ellipsis.length) {
						titleLength = $ellipsis.outerWidth(),
						anchorLength = $select.next().outerWidth();

						if ($select.data('disabled')) {
							$select.find('.ui-selectmenu-ellipsis-overlay').show();
						}

						if ((titleLength + 60) > anchorLength) {
							$select.next().find('.ui-selectmenu-ellipsis-overlay').show();
							var words = $ellipsis.text().split(' '), tries = 0;
							do {
								tries++;
								words.pop();
								$ellipsis.html(words.join(' '));
							} while( (($ellipsis.outerWidth() + 60) > anchorLength) && (tries < 10));
							$ellipsis.get(0).innerHTML += '...';
						}
					}
				});
			},

			_resize : function(){
				if (this.options.fancyDropdowns) {
					var selects = this.elements.$dropdowns
					.find('select')
					.selectmenu('destroy')
					.selectmenu(this.options.selectmenuConfig)
					.end().find('.ui-selectmenu').css({ opacity: 1 })
					.end().find('select');
					this.dropdowns._buildEllipsis(selects);
				}
			},

			_destroy : function(){
				this.$obj.find('select').selectmenu("destroy");
				this.elements.$dropdowns.empty();
			},

			_reset : function(callback){
				var self = this;
				this._abortRequest();
				this.elements.$dropdowns.animate({ height: 0, opacity: 0}, this.options.animateSpeed, function(){
					self.dropdowns._destroy.call(self);
					self.elements.$dropdowns.css({ opacity: 1 });
					(callback) && callback();
				 });
			},

			_show : function($select, callback, speed){

				var speed = this.options.animate ? speed : 0;

				// show the dropdowns container
				var height = this.elements.$dropdowns.height();
				this.elements.$dropdowns.css({ height: 'auto' });
				this.elements.$dropdowns.find('.complaints-select-container:last').show();
				this.elements.$dropdowns
					.data('height', this.elements.$dropdowns.height())
					.height(height)
					.animate({ height: this.elements.$dropdowns.data('height') }, speed, callback);

				// show the selectmenu
				if ($select && this.options.fancyDropdowns) {
					$select.next().css({ opacity: 1});
				}
			},

			events : {
		
				_change : function(e, ui) {

					var self = this, child, found = false,
					select = e.target, 
					option = select.options[select.selectedIndex], 
					asset_id = $(option).attr('rel');

					if (asset_id != '0') {
						this.data.asset_id = asset_id;
					}
					
					// abort pending request
					self._abortRequest();
				
					if (self['$loading']) {
						self.$loading.remove();
					}

					// changing a disabled selectmenu	
					if ($(select).data('disabled')) {
						// remove the target buttons
						this.$obj.find('.complaints-target-buttons').remove();
						// remove sibling selectmenus 
						this.elements.$dropdowns.find('select').each(function(i){
							if (found){
								var $parent = $(this).parent();
								$(this).selectmenu('destroy').remove();
								$parent.remove();
								delete self.elements.dropdowns[i];
							}
							if (select.id == this.id) {
								found = true;
							}
						});
					} 
					else {
						// store the select label text for later use (we're using the first option for this)
						$(select).data('label', $(select.options[0]).val());
					}
					
					// disable the current dropdown
					$(select).next()
					.addClass(!this.options.fancyDropdowns ? '' : 'ui-cf-state-disabled')
					.end().data('disabled', 1)
					.addClass('ui-cf-state-disabled');
					
					this.dropdowns._buildEllipsis([e.target]);

					// get next set of dropdown data
					var child = this.options.processData.getChild(option.id, $(select).data('data_id'));
					

					if (child) {
						// build the next drodown
						self.dropdowns._build.call(self, child.id);
					} else if (self.data.asset_id) {
						// load the target page
						self._loadTarget.call(self, self.data.asset_id);
					}
				},
				_open : function(e, ui) {
					if ($(e.target).data('disabled')){

						// if opening a disabled selectmenu, show the original select label
						$(e.target)
						.data('label-orig', $(e.target).val())
						.next()
						.removeClass('ui-cf-state-disabled')
						.find('.ui-selectmenu-ellipsis')
							.html($(e.target).data('label'))
						.end().find('.ui-selectmenu-ellipsis-overlay').hide();

						// scrol the dropdown to selected li's position
						var selectmenu = $(e.target).data('selectmenu'), list = selectmenu.list, li = list.find('li').get(ui.value), position = $(li).position();
						list.scrollTop(position.top);
					}
				},
				_close : function(e, ui) {
					if ($(e.target).data('disabled')) {
						// if closing a disabled selectmenu, and option is not changed, then reset the select label back to option value
						if ($(e.target).data('label-orig') == $(e.target).val()){
							$(e.target).next()
							.find('.ui-selectmenu-ellipsis')
							.html($(e.target).data('label-orig'));
							this.dropdowns._buildEllipsis([e.target]);
						}
						$(e.target).next().addClass('ui-cf-state-disabled');
					}
				}
			}

		},

		_abortRequest : function(){
			(this.xhr) && (this.xhr.abort());
		},

		_getTargetURL : function(asset_id, callback){
			this._abortRequest();
			// get the target URL for specified asset
			this.xhr = $.ajax({
				type: 'GET',
				url: this.options.assetUrl,
				data: 'asset_id=' + asset_id,
				cache: false,
				dataType: 'html',
				error: function(xhr, textStatus, error){
					alert('Sorry, an unexpected error occurred.');
				},
				success: function(data, textStatus, xhr){
					(data) && (callback) && callback(data);
				}
			});
		},

		_loadTarget : function(asset_id){

			var self = this;

			// build & show loading spinner
			this.$loading = $('<div class="complaints-filter-loading"></div>');
			this.elements.$select.next().next().after(this.$loading);
			this.dropdowns._show.call(this);
			
			this._getTargetURL(asset_id, function(url){

				// remove loading spinner
				self.$loading.remove();
				delete self['$loading'];

				if (self.options.targetAutoload) {
					window.location = url;
					return;
				} else {

					// show the target buttons
					self.elements.$dropdowns.append(self.elements.$targetButtons);
					self.dropdowns._show.call(self);

					self.elements.$targetButtons
					.find('.more-info').unbind('click')
					.click(function(){
						// load the target page
						window.location = url;
						return false;
					}).end()
					.find('.start-again').unbind('click')
					.click(function(){
						// reset the dropdowns
						self.dropdowns._reset.call(self, function(){
							self.dropdowns._build.call(self);
						});
						return false;
					});
				}
			});
		}
	};

	$.pdata = {

		data: [], optionParents: [], dropdownParents: [],

		add: function(obj) {
			this.data.push(obj);
			return this;
		},
		setParentOption: function(index){
			// fixme
			this.optionParents.push({ id: (this.data.length - 1), parent: index });
		},
		setParentDropdown: function(index){
			this.dropdownParents.push({ id: (this.data.length - 1), parent: index });
		},
		get: function(id){
			id = id || 0;
			return $.grep(this.data, function(n, i){
				return (Number === id.constructor) ? (id === i) : (n.id === id);
			})[0];
		},
		getChild: function(option_id, dropdown_id){
			option_id = option_id || 0;
			dropdown_id = dropdown_id || 0;

			// search for option child sets first
			var child =  $.grep(this.optionParents, function(n){
				return (n.parent == option_id);	
			})[0];
			if (child) return child;

			// search for dropdown child sets
			return $.grep(this.dropdownParents, function(n){
				return (n.parent == dropdown_id);
			})[0];
		}
	};


	$.fn.tooltip = function(options){
		return this.each(function(){
			(!$(this).data('tooltip')) && 
				$(this).data('tooltip', new $.ToolTip(this, options));
		});
	};

	$.ToolTip = function(element, options){
		this.$element = $(element);
		this.elements = {};
		this.options = $.extend({
			delay: 500,
			showSpeed: 200,
			maxWidth: 240,
			position: "left" // left; bottom; right; auto
		}, options);
		this.timer = null;
		this.init();
	};

	$.ToolTip.prototype = {
		
		init : function(){
			var self = this;
			this.buildElements();
			this.bindEvents();
			$().mousemove(function(e){
				self.otions.mouseX = e.pageX;
				self.options.mouseY = e.pageY;
			}); 
		},

		buildElements : function(){
			var self = this;
			this.elements.$tooltip = 
				$(".tooltip-container").length ? $(".tooltip-container:first") : 
				$("<div/>").addClass("tooltip-container").css({opacity: 0}).prependTo("body");

		},

		bindEvents : function(){
			var self = this, 
			$hoverElement = this.$element;

			$hoverElement.each(function(key){
				if (!this.title) return true;

				// store title in element data
				$.data(this, "title", this.title.replace(/\n/g, '<br />'));

				$(this)
				// remove title to prevent default browser tooltip
				.removeAttr("title")
				// remove alt to prevent alt tooltip in IE
				.removeAttr("alt")
				// bind hover events
				.mouseenter(function(event){
					self.showTooltip(this);
				})
				.mouseleave(function(event){
					self.hideTooltip(this);
				})
				.mousedown(function(){
					self.hideTooltip(this);
				});
			});
		},

		showTooltip : function(element){
			var self = this, left, top, $element = $(element), offset = $element.offset(), title = $.data(element, "title");

			// get browser viewport dimensions
			var viewport = {
				width : window.innerWidth ? window.innerWidth : $(window).width(),
				height : window.innerHeight ? window.innerHeight : $(window).height()
			};
			
			// display the tooltip
			self.timer = setTimeout(function(){
				// append the tooltip message and set the width
				self.elements.$tooltip
				.html(title)
				.css({
					width: self.elements.$tooltip.outerWidth() > self.options.maxWidth ? self.options.maxWidth : "auto"
				});

				var coords = self.getCoords(self.options.position, $element, offset, viewport);

				// position the tooltip
				self.elements.$tooltip
				.css({left: coords.left, top: coords.top, opacity:0})
				.show().animate({opacity: 1}, self.options.showSpeed);

			}, self.options.delay);
		},
		
		getCoords: function(position, $element, offset, viewport) {
			var self = this;

			// remove the tooltip container class names
			$.each(['left', 'top', 'right', 'bottom', 'auto'], function(key, val){
				self.elements.$tooltip.removeClass("tooltip-"+val);
			});
			// add the appropriate class name
			this.elements.$tooltip.addClass("tooltip-"+position);

			switch(position) {
				case "left": 
					if (offset.left - this.elements.$tooltip.outerWidth() < 0) {
						// tooltip is outside viewport
						return this.getCoords("right", $element, offset, viewport);
					}
					return {
						left : offset.left - this.elements.$tooltip.outerWidth(),
						top : (offset.top - (this.elements.$tooltip.outerHeight() / 2)) + ($element.outerHeight() / 2)
					};
				case "right":
					if (($element.outerWidth() + offset.left + this.elements.$tooltip.outerWidth()) > viewport.width) {
						// tooltip is outside viewport
						return this.getCoords("left", $element, offset, viewport);
					};
					return {
						left : offset.left + $element.outerWidth(),
						top : (offset.top - (this.elements.$tooltip.outerHeight() / 2)) + ($element.outerHeight() / 2)
					};
				case "bottom":
					return {
						left : (offset.left - (this.elements.$tooltip.outerWidth() / 2)) + ($element.outerHeight() / 2),
						top : (offset.top + $element.outerHeight())
					};
				case "auto":
					return {
						left: (this.options.mouseX - (this.elements.$tooltip.outerWidth() / 2)) + ($element.outerHeight() / 2) + 10,
						top: (offset.top + $element.outerHeight())
					};
				default:;
			}
		},

		hideTooltip : function(){
			clearTimeout(this.timer);
			this.elements.$tooltip.stop().css({opacity: 0, left: -9999, width: "auto"});
		}
	};
	
	$.isMobileDevice = function(){
		var mobile = false, uagent = window.navigator.userAgent.toLowerCase();
		var uagentStrings = [ 'iphone', 'ipod', 'android', 'symbian', 'series60', 'series70', 'series80', 'series90', 'windows ce', 'iemobile', 'wm5 pie', 'blackberry', 'vnd.rim', 'palm', 'webos', 'blazer', 'xiino', 'mobile', 'pda' ];
		$.each(uagentStrings, function(){
			if (new RegExp(this, 'i').test(uagent)){
				mobile = true;
				return false; // break
			}
		});
		return mobile;
	};

	$.browserFix = function(){
		$.isMobile = $.isMobileDevice();
		$.isIE6 = ($.browser.msie && $.browser.version.substr(0,1) < 7);
		if ($.isIE6) {
			// fix for flickering bg images
			try { document.execCommand('BackgroundImageCache', false, true); }
			catch(e) {};
		}
	};

	$.equalHeights = function(){
		var $cols = $(".middle-feature"), resizeTimer = null;
		if ($cols.length && $().equalHeights) {
			$cols.equalHeights(".feature", true);
			$(window).bind('resize', function() {
				(resizeTimer) && clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function() {
					$cols.equalHeights(".feature", true);
				}, 100);
			});
		}
		return this;
	};

	$.fn.toggleArchive = function(options){
		options = $.extend({
			toggleClass: 'toggle-open',
			selector: '.topspan'
		}, options || {});

		return this.each(function(){
			$(this).find(options.selector).click(function(i){
				$(this).next().toggle().end().toggleClass(options.toggleClass);
			});
		});
	};
	
	new $.browserFix();





	// document ready
	$(function(){
		$("#nav").toggleNav({ speed: 220 });
		$("#searchtext, #searchpanel-text").toggleField();
		$("#text-size").textsize();

               
                // M Jakda 23 / 07 / 2010 To make Resize of text persist during whole of user session 
                if($.cookie('resizecookie') != null){
		   // set body fontsize to value in cookie
		   cookieSize = $.cookie('resizecookie');
		   $('body').css({fontSize: cookieSize});          			
		}

                // M Jakda 21/09/2010 To remove ref tag that refs CSS file in Header section
                $("#text-version").textVersion();
                // M Jakda 22/09/2010 To replace ref tag that refs CSS file in Header section for CSS file that has contrast
                $("#contrast-version").contrastVersion();

		$("#aside-categories").toggleArchive({
			selector: '.topspan',
			toggleClass: 'toggle-open'
		});
		$("#language-slideshow .slideshow").jCarouselLite({
			vertical: true,
			hoverPause: true,
			visible: 1,
			auto: 500,
			speed: 1000,
			btnNext: ".slideshow-next",
			btnPrev: ".slideshow-prev"
		});
		(!$.isMobile) && $('select.sq-form-field').selectmenu({
			width: 300,
			menuWidth: 300,
			maxHeight: 200,
			showFirstOption: true,
			transferClasses: true,
			style: 'dropdown'
		});
		$.equalHeights();
	});

})(jQuery);

