
function checkWallpaper() {

	// check for Grid layout
	var bIsGridLayout = true;
	if ($("#mf_sky").length) {
		bIsGridLayout = false;
	}

	var adWidth = 728;
	var adHeight = 90;

	// check for wallpaper type
	if (typeof(adtype) != 'undefined' && adtype == 'wallpaper') {

		// Turn on placeholder and get position
		$("#mhLeaderBoard").show();
		var LeaderBoardPlaceholder = $("#mhLeaderBoard").position();
		$("#mhLeaderBoard").hide();

		if (bIsGridLayout) {
			//newWorld
			$("#mhHeaderTopWrapper").show();
			$("#mhLeaderBoardPreLoad").addClass("LeaderBoardVisible").css("top", LeaderBoardPlaceholder.top + "px").css("left", "252px").show();
			$("#wrapper").css("padding", adHeight + "px 0 0 0");

			$("#SkyScraper").css('margin-top', '-' + adHeight + 'px');

		} else {
			//oldWorld
			$("#mhLeaderBoardPreLoad").addClass("LeaderBoardVisible").css("top", LeaderBoardPlaceholder.top + "px").css("left", "268px").show();
			$("#wrapper").css("padding", adHeight + "px 0 0 0");
			$("#mhHeaderTopWrapper").show();
			$("#mf_sky").css("top", LeaderBoardPlaceholder.top + "px");

		}

		// check for background color change
		if (typeof(bgcolor) != 'undefined' && bgcolor != null) {
			$("#wrapper, #mhLeaderBoard, #SkyScraper, #mf_sky").css('background', bgcolor);
		}

	} else if (typeof(adtype) != 'undefined' && adtype == 'expwallpaper') {
		// not available yet
	} else {
		if (typeof(adtype) != 'undefined' && adtype == 'doublelb') {
			adHeight = 180;
		}
		// check for existing leaderboard
		if ($("#mhLeaderBoardPreLoad").width() > 0 && $("#mhLeaderBoardPreLoad").height() > 0) {
			// Turn on placeholder and get position
			$("#mhLeaderBoard").show();
			var LeaderBoardPlaceholder = $("#mhLeaderBoard").position();
			$("#mhLeaderBoard").hide();

			if (bIsGridLayout) {

				$("#mhHeaderTopWrapper").show();
				$("#mhLeaderBoardPreLoad")
					.addClass("LeaderBoardVisible")
					.css("top", (LeaderBoardPlaceholder.top + 10) + "px").css("left", "126px").show();
				$("#wrapper").css("padding", (adHeight + 10) + "px 0 0 0");

			} else {
				$("#mhLeaderBoardPreLoad")
					.addClass("LeaderBoardVisible")
					.css("top", (LeaderBoardPlaceholder.top + 10) + "px").css("left", "126px").show();
				$("#wrapper").css("padding", (adHeight + 10) + "px 0 0 0");
				$("#mf_sky").css("top", (LeaderBoardPlaceholder.top + adHeight + 60) + "px");
				$("#mhHeaderTopWrapper").show();
			}
		}

	}

	// check for background image
	if (typeof(bgimage) != 'undefined' && bgimage != null) {
		// not available yet
	}

	// check for background click
	if (typeof(adclick) != 'undefined' && adclick != null) {
		// not available yet
	}

	$("#mhContent").css("min-height", "620px").css("_height", "620px");

}

// Replaces href with name attribute for SEO purpose
$(document).ready(function() {
    $(".mhLinkReplacement").each(function(){
        var currentLink = $(this).attr("name");
        $(this).attr("href", currentLink).removeClass("mhLinkReplacement");
    });

	checkWallpaper();
});

/*! http://mths.be/placeholder v1.8.5 by @mathias */
(function(g,a,$){var f='placeholder' in a.createElement('input'),b='placeholder' in a.createElement('textarea');if(f&&b){$.fn.placeholder=function(){return this};$.fn.placeholder.input=$.fn.placeholder.textarea=true}else{$.fn.placeholder=function(){return this.filter((f?'textarea':':input')+'[placeholder]').bind('focus.placeholder',c).bind('blur.placeholder',e).trigger('blur.placeholder').end()};$.fn.placeholder.input=f;$.fn.placeholder.textarea=b;$(function(){$('form').bind('submit.placeholder',function(){var h=$('.placeholder',this).each(c);setTimeout(function(){h.each(e)},10)})});$(g).bind('unload.placeholder',function(){$('.placeholder').val('')})}function d(i){var h={},j=/^jQuery\d+$/;$.each(i.attributes,function(l,k){if(k.specified&&!j.test(k.name)){h[k.name]=k.value}});return h}function c(){var h=$(this);if(h.val()===h.attr('placeholder')&&h.hasClass('placeholder')){if(h.data('placeholder-password')){h.hide().next().show().focus().attr('id',h.removeAttr('id').data('placeholder-id'))}else{h.val('').removeClass('placeholder')}}}function e(){var l,k=$(this),h=k,j=this.id;if(k.val()===''){if(k.is(':password')){if(!k.data('placeholder-textinput')){try{l=k.clone().attr({type:'text'})}catch(i){l=$('<input>').attr($.extend(d(this),{type:'text'}))}l.removeAttr('name').data('placeholder-password',true).data('placeholder-id',j).bind('focus.placeholder',c);k.data('placeholder-textinput',l).data('placeholder-id',j).before(l)}k=k.removeAttr('id').hide().prev().attr('id',j).show()}k.addClass('placeholder').val(k.attr('placeholder'))}else{k.removeClass('placeholder')}}}(this,document,jQuery));

$(document).ready(function() {
    $(".InputFieldWithDeleteButton").each(function() {


        $(this).wrap('<span class="InputWrapperForDeleteFunction"></span>');

        $(this).parent(".InputWrapperForDeleteFunction").each(function() {

            $(this).append('<div class="RemoveIconForDeleteFunction"></div>');
            var $that = $(this);
            var $currentInput = $(this).find("input");
            var $currentRemoveIcon = $that.find(".RemoveIconForDeleteFunction");

            $currentInput.bind("focus", function(e) {
                    if ($currentInput.val() != "") {
                        $currentRemoveIcon.fadeIn();
                    } else {
                        $currentRemoveIcon.fadeOut();
                    }
                }).bind("blur", function(e) {
                    // check for placeholder class necessary for IE
                    if ($currentInput.val() == "" || $currentInput.hasClass("placeholder")) {
                        $currentRemoveIcon.fadeOut();
                    }
                }).bind("keyup", function() {
                    if ($currentInput.val() != "") {
                        $currentRemoveIcon.fadeIn();
                    } else {
                        $currentRemoveIcon.fadeOut();
                    }
                });

            $currentRemoveIcon.bind("click", function(e) {
                $currentInput.val("").blur();
                $currentRemoveIcon.fadeOut();
            });

            $currentInput.triggerHandler("focus");
            $currentInput.blur();

        });

    });
});

//-----------------Start----------------//
//- Low Pro port to jQuery by Dan Webb -//
//--------------------------------------//
;(function($) {
  
  var addMethods = function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = $.keys(source);

    if (!$.keys({ toString: true }).length) properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && $.isFunction(value) && $.argumentNames(value)[0] == "$super") {
        
        var method = value, value = $.extend($.wrap((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property), method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
  
  $.extend({
    keys: function(obj) {
      var keys = [];
      for (var key in obj) keys.push(key);
      return keys;
    },

    argumentNames: function(func) {
      var names = func.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(/, ?/);
      return names.length == 1 && !names[0] ? [] : names;
    },

    bind: function(func, scope) {
      return function() {
        return func.apply(scope, $.makeArray(arguments));
      }
    },

    wrap: function(func, wrapper) {
      var __method = func;
      return function() {
        return wrapper.apply(this, [$.bind(__method, this)].concat($.makeArray(arguments)));
      }
    },
    
    klass: function() {
      var parent = null, properties = $.makeArray(arguments);
      if ($.isFunction(properties[0])) parent = properties.shift();

      var klass = function() { 
        this.initialize.apply(this, arguments);
      };

      klass.superclass = parent;
      klass.subclasses = [];
      klass.addMethods = addMethods;

      if (parent) {
        var subclass = function() { };
        subclass.prototype = parent.prototype;
        klass.prototype = new subclass;
        parent.subclasses.push(klass);
      }

      for (var i = 0; i < properties.length; i++)
        klass.addMethods(properties[i]);

      if (!klass.prototype.initialize)
        klass.prototype.initialize = function() {};

      klass.prototype.constructor = klass;

      return klass;
    },
    delegate: function(rules) {
      return function(e) {
        var target = $(e.target), parent = null;
        for (var selector in rules) {
          if (target.is(selector) || ((parent = target.parents(selector)) && parent.length > 0)) {
            return rules[selector].apply(this, [parent || target].concat($.makeArray(arguments)));
          }
          parent = null;
        }
      }
    }
  });
  
  var bindEvents = function(instance) {
    for (var member in instance) {
      if (member.match(/^on(.+)/) && typeof instance[member] == 'function') {
        instance.element.bind(RegExp.$1, $.bind(instance[member], instance));
      }
    }
  }
  
  var behaviorWrapper = function(behavior) {
    return $.klass(behavior, {
      initialize: function($super, element, args) {
        this.element = $(element);
        if ($super) $super.apply(this, args);
      }
    });
  }
  
  var attachBehavior = function(el, behavior, args) {
      var wrapper = behaviorWrapper(behavior);
      instance = new wrapper(el, args);

      bindEvents(instance);

      if (!behavior.instances) behavior.instances = [];

      behavior.instances.push(instance);
      
      return instance;
  };
  
  
  $.fn.extend({
    attach: function() {
      var args = $.makeArray(arguments), behavior = args.shift();
      
      if ($.livequery && this.selector) {
        return this.livequery(function() {
          attachBehavior(this, behavior, args);
        });
      } else {
        return this.each(function() {
          attachBehavior(this, behavior, args);
        });
      }
    },
    attachAndReturn: function() {
      var args = $.makeArray(arguments), behavior = args.shift();
      
      return $.map(this, function(el) {
        return attachBehavior(el, behavior, args);
      });
    },
    delegate: function(type, rules) {
      return this.bind(type, $.delegate(rules));
    },
    attached: function(behavior) {
      var instances = [];
      
      if (!behavior.instances) return instances;
      
      this.each(function(i, element) {
        $.each(behavior.instances, function(i, instance) {
          if (instance.element.get(0) == element) instances.push(instance);
        });
      });
      
      return instances;
    },
    firstAttached: function(behavior) {
      return this.attached(behavior)[0];
    }
  });
  
  Remote = $.klass({
    initialize: function(options) {
      if (this.element.attr('nodeName') == 'FORM') this.element.attach(Remote.Form, options);
      else this.element.attach(Remote.Link, options);
    }
  });
  
  Remote.Base = $.klass({
    initialize : function(options) {
      this.options = $.extend({
        
      }, options || {});
    },
    _makeRequest : function(options) {
      $.ajax(options);
      return false;
    }
  });
  
  Remote.Link = $.klass(Remote.Base, {
    onclick: function() {
      var options = $.extend({ url: this.element.attr('href'), type: 'GET' }, this.options);
      return this._makeRequest(options);
    }
  });
  
  Remote.Form = $.klass(Remote.Base, {
    onclick: function(e) {
      var target = e.target;
      
      if ($.inArray(target.nodeName.toLowerCase(), ['input', 'button']) >= 0 && target.type.match(/submit|image/))
        this._submitButton = target;
    },
    onsubmit: function() {
      var data = this.element.serializeArray();
      
      if (this._submitButton) data.push({ name: this._submitButton.name, value: this._submitButton.value });
      
      var options = $.extend({
        url : this.element.attr('action'),
        type : this.element.attr('method') || 'GET',
        data : data
      }, this.options);
      
      this._makeRequest(options);
      
      return false;
    }
  });
  
  $.ajaxSetup({ 
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    } 
  });
  
})(jQuery);
//------------------End-----------------//
//-Dan Webb's port of Low Pro to jQuery-//
//--------------------------------------//


//-----------------Start----------------//
//- InTradeSys dependencieModel:Basics -//
//--------------------------------------//

var formElement = $.klass
(
	{
		initialize: function (type, refobject, name)
		{
			this.setType(type ? type : 'formElement');
			this.setReferenceObject(refobject);
			this.setName(name);
		},
		
		setReferenceObject: function (refobject)
		{
			if (typeof refobject != 'undefined')
			{
				if (typeof refobject[0] != 'undefined')
				{
					this.setDomNode(refobject[0]);
				}
				else
				{
					this.setDomNode(refobject);
				}
			}
		},		
		
		setType: function (type)
		{
			this.type = type;
		},
		
		getType: function ()
		{
			return (this.type);
		},
		
		setName: function (name)
		{
			this.name = name;
		},
		
		getName: function ()
		{
			return (this.name);
		},

		display: function (configuration, sender)
		{
			sender = sender ? sender : null;
			useFading = configuration.useFading ? true : false;
			
			if (typeof configuration.visible != 'undefined')
			{
				configuration.visible ? this.show(useFading) : this.hide(useFading);
			}
		},
		
		show: function (useFading)
		{
			if (typeof this.domNode != 'undefined') {
				if (this.domNode && (!this.domNode.isVisible || typeof this.domNode.isVisible == 'undefined'))
				{
					this.domNode.isVisible = true;

					if (useFading)
					{
						this.getJObject().fadeIn("slow");
					}
					else
					{
						this.getJObject().show();
					}
				}
			}
		},
		
		hide: function (useFading)
		{
			if (typeof this.domNode != 'undefined') {
				if (this.domNode.isVisible || typeof this.domNode.isVisible == 'undefined')
				{
					this.domNode.isVisible = false;

					if (useFading)
					{
						this.getJObject().fadeOut("slow");
					}
					else
					{
						this.getJObject().hide();
					}
				}
			}
		},
		
		setDomNode: function (domNode)
		{
			this.domNode = domNode;
			
			domNode.owner = this;
		},
		
		getDomNode: function ()
		{
			return (this.domNode);
		},
		
		getJObject: function ()
		{
			return ($(this.domNode));
		},

		acceptWatcher: function (watcher, event, immediateFire)
		{
			var self = this;
			this.getJObject().bind
			(
				event,
				this,
				function(e)
				{
					watcher.handleWatchedEvent(watcher, self, event);
				}
			);
			
			if (immediateFire)
			{
				watcher.handleWatchedEvent(null, this, event);
			}
		},
		
		positionEditLayer: function (layerId, targetId, xOffset, yOffset)
		{
			var layerNode = $('#' + layerId);
			var withoutTarget = false;
			
			if (targetId)
			{		
				var targetNode = $('#' + targetId);
			}
			else
			{
				withoutTarget = true; 
			}
			
			if (!xOffset)
			{
				xOffset = 0;
			}
			
			if (!yOffset)
			{
				yOffset = 0;
			}
			
			if (!withoutTarget)
			{		
				var targetNodeOffsets = targetNode.offset();
				
				layerNode.css("left", targetNodeOffsets.left + xOffset - 300);
				layerNode.css("top", targetNodeOffsets.top + yOffset - 150);
			}
			else
			{
				layerNode.css("left", xOffset);
				layerNode.css("top", yOffset);
			}
		}
	}
);

var inputElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name, preventObservingEnterKey)
		{
			$super(type, domNode, name);
			
			thisObj = this;
			
			if (!preventObservingEnterKey)
			{
				this.getJObject().bind
				(
					'keypress',
					function (e)
					{
						// check for enter key to prevent form submit
						if (thisObj.observeKey(e, 13))
						{
							var srcElement = e.target; 
							
							if (srcElement.blur)
							{
								srcElement.blur();
							}
							
							//Event.stop(e);
							e.stopPropagation();
						}
					}
				);
			}
		},
		
		display: function ($super, configuration, sender)
		{
			$super(configuration, sender);
			
			if (typeof configuration.visible != 'undefined')
			{
				this.setValue(configuration.value);
			}
			
			if (configuration.disabled)
			{
				this.domNode.disabled = true;
			}
		},

		setValue: function (value)
		{
			this.getDomNode().value = value ? value : '';
		},
		
		getValue: function ()
		{
			return (this.getDomNode().value);
		},
		
		observeKey: function (e, keyToObserve)
		{
			keyToObserve = keyToObserve ? keyToObserve : 13; // 13 == enter key
			
			if (window.event)
			{
				var key = window.event.keyCode;
			}
			else if (e)
			{
				var key = e.keyCode || e.which;
			}
		
			return (key == keyToObserve);
		}
	}
);
//------------------End-----------------//
//- InTradeSys dependencieModel Basics -//
//--------------------------------------//

//-----------------Start------------------//
//- InTradeSys dependencieModel:myHammer -//
//----------------------------------------//

var textCounter = $.klass
(
	formElement,
	{
		initialize: function ($super, domNode, counterDomNode, name, valueToHide)
		{
			$super('textcounter', domNode, name);
			
			this.counterDomNode = counterDomNode;
			this.valueToHide = valueToHide;
		},
		
		setValue: function (value)
		{
			this.counterDomNode.html(''+value);
			
			value == String(this.valueToHide) ? this.hide() : this.show();
			
			if (value <= 10)
			{
				this.getJObject().css('color','#ff0000');
			}
			else
			{
				this.getJObject().css('color','#000000');
			}
		},
		
		getValue: function ()
		{
			return (this.counterDomNode.firstChild.nodeValue);
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'keyup':
				case 'change':
					switch (watchedElement.getType())
					{
						case 'limitedTextArea':
						this.setValue(watchedElement.getJObject().attr('maxChars') - watchedElement.getJObject().val().length);
						break;
						
						case 'text':
						this.setValue(watchedElement.getJObject().attr('maxlength') - watchedElement.getJObject().val().length);
						break;
					}
				break;
			}
		}
	}
);

var textElement = $.klass
(
	inputElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('text', domNode, name);
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			var watchedElementName = watchedElement.getName();

			switch (event)
			{
				case 'change':
				case 'custom:change':
				
					switch (watchedElementName)
					{
						case 'UsePhoneLocalNumber':
						case 'UsePhone2LocalNumber':
						
							if (watchedElement.domNode.checked)
							{
								this.domNode.disabled = false;
								this.domNode.focus();
							}
							else
							{
								this.domNode.disabled = true;
							}
						
							break;
					}
					
					break;
			}
		},
		
		setValue: function ($super, value, fireCustomChange)
		{
			$super(value);
			
			if (fireCustomChange)
			{
				this.domNode.trigger('custom:change');
			}
		}
	}
);

var tabElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('tabElement');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
				
					this.selectTab(watchedElement);
					break;
			}
		},
		
		selectTab: function (activeTab)
		{
			$('#tabCompanyProfil')[0].className = 'navBarTabContainer';
			$('#tabFeedback')[0].className = 'navBarTabContainer';
			$('#tabOffers')[0].className = 'navBarTabContainer';
			$('#tabReferences')[0].className = 'navBarTabContainer';

			if ($('#tabApprenticeship').size() > 0) {
				$('#tabApprenticeship')[0].className = 'navBarTabContainer';
			}
			
			activeTab.domNode.className = 'navBarTabContainerActiv';

			if (bIsOwner)			
			{
				$('.editor').each
				(
					function()
					{
						if ($(this).css('display') != 'none')
						{
							$(this).fadeOut('slow');
						}
					}
				);
			}
		}
	}
);

var pictureElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('pictureElement');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'change':
				
					break;
			}
		}
	}
);


var googleMapElement = $.klass (
	formElement, {
		initialize: function ($super, type, domNode, name) {
			$super(type, domNode, name);

			if (GBrowserIsCompatible())  {
		        this.map = new GMap2(document.getElementById("GoogleMapBox"));
		        this.map.setCenter(new GLatLng(46.950262, 2.944336), 6);
				this.map.addControl(new GHierarchicalMapTypeControl());
				this.map.enableScrollWheelZoom();
				this.geocoder = new GClientGeocoder();
			}
		},
		
	    showAddress: function (address) {
		  if (this.geocoder) {
			  var map = this.map;
			  this.geocoder.getLatLng(
	          address,
	          function(point) {
	            if (!point) {

		            var host = parseUri(document.URL).host;
		            if (host == 'branchenbuch.my-hammer.de') {
			            map.setCenter(new GLatLng(51.3, 10.10), 4);
		            }
		            if (host == 'directory.myhammer.co.uk') {
		                map.setCenter(new GLatLng(53.60, -3.61), 4);
		            }
		            if (host == 'branchenbuch.my-hammer.at') {
			            map.setCenter(new GLatLng(47.596, 13.644), 5);
		            }
	            } else {
		           	map.setCenter(point, 13);
					map.addOverlay(new GMarker(point));
	            }
	          }
	        );
	      }
	    }
	}
);

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


var textareaElement = $.klass
(
	inputElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('textarea', domNode, name, true);
		}
	}
);

var limitedTextareaElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('limitedTextArea');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'keyup':
					if(this.getJObject().val().length >= this.getJObject().attr('maxChars'))
					{
						this.getJObject().val(this.getJObject().val().substring(0,this.getJObject().attr('maxChars')));
					}
				break;
			}
		}
	}
);

//------------------End-------------------//
//- InTradeSys dependencieModel myHammer -//
//----------------------------------------//


/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.4
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'y',
		duration:1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			// Just store it, we might need it
			var win = this.parentWindow || this.defaultView,
				// If it's a document, get its iframe or the window if it's THE document
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				// Get the corresponding document
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});			
			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;
				
				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

var redPages = $.klass
(
	formElement,
	{
		currentPage: 1,
		currentPerPage: 10,
		currentSort: 'review',
		search_location: '',
		search_circle: '',

		initialize: function ($super)
		{
			$super('yellowPagesElement', $('#yellowPagesElement'), 'yellowPagesElement');
			
			this.resultsCargo = $('#results_cargo');
		},
		
		setQueryCompiled: function (queryCompiled)
		{
			this.queryCompiled = queryCompiled;
		},
		
		getQueryCompiled: function ()
		{
			return (this.queryCompiled);
		},
		
		setPerPage: function (perPage)
		{
			this.currentPerPage = perPage;
		},
		
		reFilter: function (search_location, search_circle)
		{
				this.fetchSearchResults
				(
					1,
					null,
					search_location,
					search_circle
				);
			
		},
		
		reSort: function (sort)
		{
			if (sort != this.currentSort)
			{
				this.fetchSearchResults(1, sort);
				
				if (sort == 'distance')
				{
					$('#result_filter_distance_upper').addClass('selected');
					$('#result_filter_distance_lower').addClass('selected');
					$('#result_filter_review_upper').removeClass('selected');
					$('#result_filter_review_lower').removeClass('selected');
				}
				else if (sort == 'review')
				{
					$('#result_filter_distance_upper').removeClass('selected');
					$('#result_filter_distance_lower').removeClass('selected');
					$('#result_filter_review_upper').addClass('selected');
					$('#result_filter_review_lower').addClass('selected');
				}
			}
		},
		
		fetchSearchResults: function (page, sort, search_location, search_circle, perPage)
		{
			if (!page)
			{
				page = this.currentPage;
			}
			else
			{
				this.currentPage = page;
			}
			
			if (!sort)
			{
				sort = this.currentSort;
			}
			else
			{
				this.currentSort = sort;
			}			
			
			if (!search_location)
			{
				search_location = this.search_location;
			}
			else
			{
				this.search_location = search_location;
			}		
			
			if (!search_circle)
			{
				search_circle = this.search_circle;
			}
			else
			{
				this.search_circle = search_circle;
			}				
					
					
					
			
			if (!perPage)
			{
				perPage = this.currentPerPage;
			}
			else
			{
				this.currentPerPage = perPage;
			}
			
			this.fetchData
			(
				page,
				perPage,
				sort,
				search_location,
				search_circle
			); 
			
				


		},
		
		fetchData: function (page, perPage, sort, search_location, search_circle, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameter = {};
				parameter.method = 'execute-search';
				parameter['query-compiled'] = this.getQueryCompiled();
				parameter.page = page;
				parameter.perpage = perPage;
				parameter.sort = sort;
				parameter.search_location = search_location;
				parameter.search_circle = search_circle;
			  
			
				$.get
				(
					"/v3/ajax/inline-search.php?",
					parameter, 
					function(response)
					{
						thisObj.fetchData(page, perPage, sort, search_location, search_circle, response);
					}, 
					'json'
				);
			}
			else
			{
			
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
					hide_waitingscreen();
				}
				else
				{
					this.renderResult(response);
					this.renderPager(response);

					if
					(
						response['query-compiled']
							&& response['query-compiled'] != this.getQueryCompiled()
					)
					{
						this.setQueryCompiled(response['query-compiled']);
					}
					hide_waitingscreen();
					$.scrollTo('#yellowPagesElement', 800);
					
					$.nyroModalRemove();
					
				}
			}
		},
		
		renderResult: function (result)
		{
			var thisObj = this,
				myId,
				template,
				resultTemplate = $('#result_template'),
				classSuffix,
				userTranslations;
			
			this.resultsCargo.empty();
			this.resetMap();

            $(".search_result_city").empty().text(result['search_location_city']);
            $(".search_result_city_link").empty().text(result['search_location_city']).attr('href',function(){
                return $(this).attr('href').substr(0,$(this).attr('href').lastIndexOf("/")+1) + result['search_location_city'];
            });
        
     if (result.resultdata.length == 0){
     	$('#results_bottom').hide();
     	$('#results_bar_bottom').hide();
     
    }

			for (var i = 0, c = result.resultdata.length; i < c; i++)
			{
				var id = i;
				var data = result.resultdata[i];

				userTranslations = thisObj.buildUserTranslations(data['user']);

				template = resultTemplate.clone(true);
				template.removeAttr('id');
				template[0].myId = data.hit;

				switch (data.mode)
				{
					case '2': // business
         
						template.find('#company_title_std').remove();
						template.find('#markerBubble_company_std').remove();
						template.find('#result_logopro').remove();
						template.find('#markerBubble_logopro').remove();
						template.find('#result_itemgetcontact_box').remove();
						template.find('#markerBubble_directcontact_box').remove();

						if (!data['featured_review'])
						{
							template.find('#result_ratingteaser_box').remove();
						}

						classSuffix = 'business';

						break;

					case '1': // pro

						if (data.bought)
						{
							template.find('#company_title_std').remove();
							template.find('#markerBubble_company_std').remove();
							template.find('#result_itemgetcontact_box').remove();
							template.find('#markerBubble_directcontact_box').remove();
						}
						else
						{
							template.find('#result_user\\.company_title').remove();
							template.find('#result_contanctinfos_box').remove();
							template.find('#result_itemfixday_box').remove();
							template.find('#markerBubble_result_user\\.company_title').remove();
							template.find('#markerBubble_address_box').remove();
						}

						template.find('#result_logobusiness').remove();
						template.find('#markerBubble_logobusiness').remove();
						template.find('#result_company_description_box').remove();

						if (!data['featured_review'])
						{
							template.find('#result_ratingteaser_box').remove();
						}

						classSuffix = 'pro';

						break;

					case '0': // basis
					default:

						if (data.bought)
						{
							template.find('#company_title_std').remove();
							template.find('#markerBubble_company_std').remove();
							template.find('#result_itemgetcontact_box').remove();
							template.find('#markerBubble_directcontact_box').remove();
						}
						else
						{
							template.find('#result_user\\.company_title').remove();
							template.find('#result_contanctinfos_box').remove();
							template.find('#result_itemfixday_box').remove();
							template.find('#markerBubble_result_user\\.company_title').remove();
							template.find('#markerBubble_address_box').remove();
						}

						template.find('#result_logobusiness').remove();
						template.find('#result_logopro').remove();
						template.find('#result_company_description_box').remove();
						template.find('#result_ratingteaser_box').remove();

						template.find('#markerBubble_logopro').remove();
						template.find('#markerBubble_logobusiness').remove();

						classSuffix = 'basis';

						break;
				}

				// link to profile
				template.find('#result_user\\.username').attr('href', data['user']['userUrl']);
				template.find('#markerBubble_result_user\\.username').attr('href', data['user']['userUrl']);
				template.find('#result_user\\.company_title').attr('href', data['user']['userUrl']);

				// hit_pin_url
				template.find('#result_hit_pin').addClass('partnertype-' + classSuffix).children().attr('src', data['hit_pin_url']).attr('alt', id + 1);

				// logo_url
				if (data['logo_url'])
				{
					template.find('#result_logo').children().attr('src', data['logo_url']);
				}

				// logo_url
				if (data['featured_review']['detail_average'])
				{
					template.find('#result_detail_average').attr('src', starPicUrl(data['featured_review']['detail_average']));
				}

				// timestamp_written
				if (data['featured_review']['timestamp_written'])
				{
					var date = new Date(data['featured_review']['timestamp_written'] * 1000);
					template.find('#result_timestamp_written').html(date.getDate() + '.' + date.getMonth() + '.' + date.getFullYear());
				}

				// distance
				if (!data['distance'])
				{
					template.find('#markerBubble_distance_box').remove();
				}

				// review score and review percentage
				if (data['user']['review_score'] == 0)
				{
					template.find('#result_review_percentage_box').remove();
					template.find('#markerBubble_review_percentage_box').remove();
				}
				else
				{
					template.find('#markerBubble_result_noscore').remove();

					if (data['user']['review_percentage'] > 50)
					{
						template.find('#result_review_redhammer').remove();
						template.find('#markerBubble_review_redhammer').remove();
					}
					else
					{
						template.find('#result_review_greenhammer').remove();
						template.find('#markerBubble_review_greenhammer').remove();
					}
				}

				// categories
				if
				(
					data['categories']
						&& typeof(data['categories']) == 'object'
						&& data['categories'].length > 0
						&& (data['categories'].length != 1 || data['categories'][0] != '')
				)
				{
					var catNode,
						catTemplate = template.find('#result_category_template'),
						resultCategoriesNode = template.find('#result_categories');

					for (var catI = 0, catC = data['categories'].length; catI < catC; catI++)
					{
						var catId = catI;
						var category = data['categories'][catI];

						catNode = catTemplate[0].cloneNode(true);
						catNode.id = null;
						catNode.innerHTML = category;
						catNode.style.display = '';

						resultCategoriesNode[0].appendChild(catNode);

						if (catId < data['categories'].length - 1)
						{
							resultCategoriesNode.append(', ');
						}
					}
				}
				else
				{
					template.find('#result_categories').remove();
				}

				// tags
				if
				(
					data['tags']
						&& typeof(data['tags']) == 'object'
						&& data['tags'].length > 0
						&& (data['tags'].length != 1 || data['tags'][0] != '')
				)
				{
					var tagNode,
						tagTemplate = template.find('#result_tag_template'),
						resultTagsNode = template.find('#result_tags');

					for (var tagI = 0, tagC = data['tags'].length; tagI < tagC; tagI++)
					{
						var tagId = tagI;
						var tag = data['tags'][tagI];

						tagNode = tagTemplate[0].cloneNode(true);
						tagNode.id = null;
						tagNode.innerHTML = tag;
						tagNode.style.display = '';

						resultTagsNode[0].appendChild(tagNode);

						if (tagId < data['tags'].length - 1)
						{
							resultTagsNode.append(', ');
						}
					}
				}
				else
				{
					template.find('#result_tags').remove();
				}

				// distance
				if (!data['distance'])
				{
					template.find('#result_distance_box').remove();
				}

				template = thisObj.fillTemplate(template, data, data['geo_latitude'] && data['geo_longitude']);
				thisObj.resultsCargo[0].appendChild(template[0]);
				thisObj.attachEventHandler(template, data['user'], userTranslations);

				if (data['geo_latitude'] && data['geo_longitude'])
				{
					thisObj.attachToGMResultList
					(
						data,
						template,
						"resultsLayerElement.requestOffer(this, '" + data['user']['userID'] + "', '" + userTranslations['REQUEST_OFFER_INFO'] + "', '" + userTranslations['REQUEST_OFFER_INFO_NOTICE'] + "', '" + userTranslations['REQUEST_OFFER_NO_OFFER_INFO'] + "', '" + userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE'] + "')",
						"resultsLayerElement.requestContactData(this, '" + data['user']['userID'] + "')"
					);
				}

				template.find('#markerBubble_template').remove();
			}

			this.initializeMap();

			if (result.resultdata.length == 0)
			{
				map.setCenter(new GLatLng(defaultMapCenter.lat, defaultMapCenter.lan), defaultMapCenter.zoom);
			}

			var centerWrapperObject = $('#center-wrapper'),
				gmScrollerHeight = $('#gmscroller').height();

			if (centerWrapperObject.height() < gmScrollerHeight)
			{
				centerWrapperObject.height(gmScrollerHeight + 'px');
			}
			else
			{
				centerWrapperObject.height('auto');
			}
		},

		buildUserTranslations: function (userData)
		{
			var userTranslations =
			{
				APPOINTMENT_HEADLINE: APPOINTMENT_HEADLINE_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				APPOINTMENT_INFO: APPOINTMENT_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				APPOINTMENT_DEFAULT_TEXT: APPOINTMENT_DEFAULT_TEXT_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				REQUEST_OFFER_INFO: REQUEST_OFFER_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				REQUEST_OFFER_INFO_NOTICE: REQUEST_OFFER_INFO_NOTICE_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				REQUEST_OFFER_NO_OFFER_INFO: REQUEST_OFFER_NO_OFFER_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
				REQUEST_OFFER_NO_OFFER_INFO_NOTICE: REQUEST_OFFER_NO_OFFER_INFO_NOTICE_TPL.replace(/##CONTACTTITLE##/g, userData['username'])
			};

			return (userTranslations);
		},

		attachEventHandler: function (template, userData, userTranslations)
		{
			if (!bAnonymousVisitor)
			{
				template.find('#make_appointment_link').click
				(
					function ()
					{
						resultsLayerElement.makeAppointment
						(
							this,
							userData['userID'],
							userTranslations['APPOINTMENT_HEADLINE'],
							userTranslations['APPOINTMENT_INFO'],
							userTranslations['APPOINTMENT_DEFAULT_TEXT']
						);
					}
				);

				template.find('#request_offer_link1').click
				(
					function ()
					{
						resultsLayerElement.requestOffer
						(
							this,
							userData['userID'],
							userTranslations['REQUEST_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_INFO_NOTICE'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE']
						);
					}
				);

				template.find('#request_offer_link2').click
				(
					function ()
					{
						resultsLayerElement.requestOffer
						(
							this,
							userData['userID'],
							userTranslations['REQUEST_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_INFO_NOTICE'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE']
						);
					}
				);
			}

			template.find('#request_contact_data_link').click
			(
				function ()
				{
					resultsLayerElement.requestContactData
					(
						this,
						userData['userID']
					);
				}
			);

			template.mouseover
			(
				function ()
				{
					GMInfoWindow(this.myId);
				}
			);
		},

		resetMap: function ()
		{
			active_marker_idx = -1
			map.clearOverlays();
			GMResultList = {};
		},

		initializeMap: function ()
		{
			initializeMap();
		},

		attachToGMResultList: function (result, template, requestOfferOnclickJs, requestContactOnclickJs)
		{
			GMResultList[result.hit] =
			{
				longitude: result['geo_longitude'],
				latitude: result['geo_latitude'],
				markerimage: result['hit_pin_url'],
				html: template.find('#markerBubble_template')[0].cloneNode(true),
				requestOfferOnclick: requestOfferOnclickJs,
				requestContactOnclick: requestContactOnclickJs
			};
		},

		renderPager: function (result)
		{
			var jObj = this.getJObject(),
				pagerPages = jObj.find('#pager_pages'),
				pageTemplate = $('#pager_page_template'),
				resultPageCurrent = parseInt(result['page_current']),
				resultPagePerpage = parseInt(result['page_perpage']),
				resultTotalResults = parseInt(result['total_results']),
				startPage = resultPageCurrent >= 5 ? resultPageCurrent - 4 : 1,
				endPage = Math.ceil(resultTotalResults / resultPagePerpage) - resultPageCurrent >= 5 ? resultPageCurrent + 4 : Math.ceil(resultTotalResults / resultPagePerpage),
				firstShownResult = (resultPageCurrent - 1) * resultPagePerpage + 1,
				lastShownResult = (resultPageCurrent - 1) * resultPagePerpage + result['resultdata'].length;

			if (resultTotalResults == 0)
			{
				firstShownResult = 0;
				lastShownResult = 0;

			}

			jObj.find('#pager_first_result_upper').html(String(firstShownResult));
			jObj.find('#pager_last_result_upper').html(String(lastShownResult));
			jObj.find('#pager_total_results_upper').html(String(resultTotalResults));

			jObj.find('#pager_first_result_lower').html(String(firstShownResult));
			jObj.find('#pager_last_result_lower').html(String(lastShownResult));
			jObj.find('#pager_total_results_lower').html(String(resultTotalResults));

			pagerPages.empty();

			if (startPage > 1)
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');
				page.addClass('results-page');
				page.html('<a href="javascript:redPages.fetchSearchResults(' + (startPage - 5 > 1 ? startPage - 5 : 1) + ');">&lt;&lt;</a> ');

				pagerPages.append(page);
			}

			for (var i = startPage; i <= endPage; i++)
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');

				if (resultPageCurrent == i)
				{
					page.addClass('results-active-page');
					page.html(i + ' ');
				}
				else
				{
					page.addClass('results-page');
					page.html('<a href="javascript:redPages.fetchSearchResults(' + i + ');">' + i + '</a> ');
				}

				pagerPages.append(page);
			}

			if (endPage < Math.ceil(resultTotalResults / resultPagePerpage))
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');
				page.addClass('results-page');
				page.html('<a href="javascript:redPages.fetchSearchResults(' + (endPage + 5 < Math.ceil(resultTotalResults / resultPagePerpage) ? endPage + 5 : Math.ceil(resultTotalResults / resultPagePerpage)) + ');">&gt;&gt;</a>');

				pagerPages.append(page);
			}
		},

		fillTemplate: function (template, data, hasLocation, prefix)
		{
			var thisObj = this;

			prefix = prefix ? prefix : '';

			jQuery.each
			(
				data,
				function (id, value)
				{
					if (value && typeof(value) == 'object')
					{
						template = thisObj.fillTemplate(template, value, hasLocation, prefix + id + '\\.');
					}
					else
					{
						if (jQuery.trim(String(value)).length > 0)
						{
							var resultNode = template.find('#result_' + prefix + id)[0];
							var resultNodeContainer = template.find('#result_' + prefix + id + '_container')[0];

							if (resultNode)
							{
								resultNode.innerHTML = value;
								resultNode.style.display = '';
							}

							if (resultNodeContainer)
							{
								resultNodeContainer.style.display = '';
							}

							//template.find('#result_' + prefix + id).show().html(value);
							//template.find('#result_' + prefix + id + '_container').show();

							if (hasLocation)
							{
								var markerBubbleNode = template.find('#markerBubble_result_' + prefix + id)[0];
								var markerBubbleNodeContainer = template.find('#markerBubble_result_' + prefix + id + '_container')[0];

								if (markerBubbleNode)
								{
									markerBubbleNode.innerHTML = value;
									markerBubbleNode.style.display = '';
								}

								if (markerBubbleNodeContainer)
								{
									markerBubbleNodeContainer.style.display = '';
								}

								//template.find('#markerBubble_result_' + prefix + id).show().html(value);
								//template.find('#markerBubble_result_' + prefix + id + '_container').show();
							}
						}
					}
				}
			);

			return (template);
		}
	}
);


var yellowPages = $.klass
(
	formElement,
	{
		currentPage: 1,
		currentPerPage: 10,
		currentSort: 'review',
		filter:
		{
			"filter-name": false,
			"filter-positive": false,
			"filter-subscription": false
		},

		initialize: function ($super)
		{
			$super('yellowPagesElement', $('#yellowPagesElement'), 'yellowPagesElement');

			this.resultsCargo = $('#results_cargo');
		},

		setQueryCompiled: function (queryCompiled)
		{
			this.queryCompiled = queryCompiled;
		},

		getQueryCompiled: function ()
		{
			return (this.queryCompiled);
		},

		setPerPage: function (perPage)
		{
			this.currentPerPage = perPage;
		},

		reFilter: function (filter, value)
		{
			if (!this.filter[filter] || this.filter[filter] != value)
			{
				dummyFilter = this.filter;
				dummyFilter[filter] = value ? value : false;

				this.fetchSearchResults
				(
					1,
					null,
					dummyFilter
				);
			}
		},

		reSort: function (sort)
		{
			
			if (sort != this.currentSort)
			{
				this.fetchSearchResults(1, sort);

				if (sort == 'distance')
				{
					$('#result_filter_distance_upper').addClass('selected');
					$('#result_filter_distance_lower').addClass('selected');
					$('#result_filter_review_upper').removeClass('selected');
					$('#result_filter_review_lower').removeClass('selected');
				}
				else if (sort == 'review')
				{
					$('#result_filter_distance_upper').removeClass('selected');
					$('#result_filter_distance_lower').removeClass('selected');
					$('#result_filter_review_upper').addClass('selected');
					$('#result_filter_review_lower').addClass('selected');
				}
			}
		},

		fetchSearchResults: function (page, sort, filter, perPage)
		{
			if (!page)
			{
				page = this.currentPage;
			}
			else
			{
				this.currentPage = page;
			}

			if (!sort)
			{
				sort = this.currentSort;
			}
			else
			{
				this.currentSort = sort;
			}

			if (!filter)
			{
				filter = this.filter;
			}
			else
			{
				this.filter = filter;
			}

			if (!perPage)
			{
				perPage = this.currentPerPage;
			}
			else
			{
				this.currentPerPage = perPage;
			}

			this.fetchData
			(
				page,
				perPage,
				sort,
				filter
			);


		},

		fetchData: function (page, perPage, sort, filter, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameter = {};
				parameter.method = 'execute-search';
				parameter['query-compiled'] = this.getQueryCompiled();
				parameter.page = page;
				parameter.perpage = perPage;
				parameter.sort = sort;

				jQuery.each
				(
					filter,
					function (name, value)
					{
						if (value)
						{
							if (name == 'filter-name')
							{
								var text = $('#filter_location_text').val();

								if (jQuery.trim(text))
								{
									parameter[name] = text;
								}
								else
								{
									parameter[name] = 0;
								}
							}
							else
							{
								parameter[name] = 1;
							}
						}
						else
						{
							parameter[name] = 0;
						}
					}
				);

				$.get
				(
					"/v3/ajax/inline-search.php?",
					parameter,
					function(response)
					{
						thisObj.fetchData(page, perPage, sort, filter, response);
						copyResultsBanner();
					},
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.renderResult(response);
					this.renderPager(response);

					if
					(
						response['query-compiled']
							&& response['query-compiled'] != this.getQueryCompiled()
					)
					{
						this.setQueryCompiled(response['query-compiled']);
					}

					$.scrollTo('#yellowPagesElement', 800);
				}
			}
		},

		renderResult: function (result)
		{
			var thisObj = this,
				myId,
				template,
				resultTemplate = $('#result_template'),
				classSuffix,
				userTranslations;

			this.resultsCargo.empty();
			this.resetMap();

			for (var i = 0, c = result.resultdata.length; i < c; i++)
			{
				var id = i;
				var data = result.resultdata[i];
				
				userTranslations = thisObj.buildUserTranslations(data['user']);
				
				template = resultTemplate.clone(true);
				template.removeAttr('id');
				template[0].myId = data.hit;

				switch (data.mode)
				{
					case '2': // business

						template.find('#company_title_std').remove();
						template.find('#markerBubble_company_std').remove();
						template.find('#result_logopro').remove(); 
						template.find('#markerBubble_logopro').remove(); 
						template.find('#result_itemgetcontact_box').remove();
						template.find('#markerBubble_directcontact_box').remove();
						
						if (!data['featured_review'])
						{
							template.find('#result_ratingteaser_box').remove(); 
						}

						classSuffix = 'business';

						break;

					case '1': // pro
					
						if (data.bought)
						{
							template.find('#company_title_std').remove();
							template.find('#markerBubble_company_std').remove();
							template.find('#result_itemgetcontact_box').remove();
							template.find('#markerBubble_directcontact_box').remove();
						}
						else
						{
							template.find('#result_user\\.company_title').remove();
							template.find('#result_contanctinfos_box').remove();
							template.find('#result_itemfixday_box').remove();
							template.find('#markerBubble_result_user\\.company_title').remove();
							template.find('#markerBubble_address_box').remove();
						}
						
						template.find('#result_logobusiness').remove(); 
						template.find('#markerBubble_logobusiness').remove(); 
						template.find('#result_company_description_box').remove(); 
					
						if (!data['featured_review'])
						{
							template.find('#result_ratingteaser_box').remove(); 
						}

						classSuffix = 'pro';

						break;

					case '0': // basis
					default:

						if (data.bought)
						{
							template.find('#company_title_std').remove();
							template.find('#markerBubble_company_std').remove();
							template.find('#result_itemgetcontact_box').remove();
							template.find('#markerBubble_directcontact_box').remove();
						}
						else
						{
							template.find('#result_user\\.company_title').remove();
							template.find('#result_contanctinfos_box').remove();
							template.find('#result_itemfixday_box').remove();
							template.find('#markerBubble_result_user\\.company_title').remove();
							template.find('#markerBubble_address_box').remove();
						}

						template.find('#result_logobusiness').remove(); 
						template.find('#result_logopro').remove(); 
						template.find('#result_company_description_box').remove(); 
						template.find('#result_ratingteaser_box').remove(); 

						template.find('#markerBubble_logopro').remove(); 
						template.find('#markerBubble_logobusiness').remove(); 

						classSuffix = 'basis';

						break;
				}
				
				// link to profile
				template.find('#result_user\\.username').attr('href', data['user']['userUrl']);
				template.find('#markerBubble_result_user\\.username').attr('href', data['user']['userUrl']);
				
				// hit_pin_url
				template.find('#result_hit_pin').addClass('partnertype-' + classSuffix).children().attr('src', data['hit_pin_url']).attr('alt', id + 1);
				
				// logo_url
				if (data['logo_url'])
				{
					template.find('#result_logo').children().attr('src', data['logo_url']);
				}
				
				// logo_url
				if (data['featured_review']['detail_average'])
				{
					template.find('#result_detail_average').attr('src', starPicUrl(data['featured_review']['detail_average']));
				}

				// timestamp_written
				if (data['featured_review']['timestamp_written'])
				{
					var date = new Date(data['featured_review']['timestamp_written'] * 1000);
					template.find('#result_timestamp_written').html(date.getDate() + '.' + date.getMonth() + '.' + date.getFullYear());
				}
				
				// distance
				if (!data['distance'])
				{
					template.find('#markerBubble_distance_box').remove();
				}

				// review score and review percentage
				if (data['user']['review_score'] == 0)
				{
					template.find('#result_review_percentage_box').remove();
					template.find('#markerBubble_review_percentage_box').remove();
				}
				else
				{
					template.find('#markerBubble_result_noscore').remove();
				
					if (data['user']['review_percentage'] > 50)
					{
						template.find('#result_review_redhammer').remove();
						template.find('#markerBubble_review_redhammer').remove();
					}
					else
					{
						template.find('#result_review_greenhammer').remove();
						template.find('#markerBubble_review_greenhammer').remove();
					}
				}

				// categories
				if
				(
					data['categories']
						&& typeof(data['categories']) == 'object'
						&& data['categories'].length > 0
						&& (data['categories'].length != 1 || data['categories'][0] != '')
				)
				{
					var catNode,
						catTemplate = template.find('#result_category_template'),
						resultCategoriesNode = template.find('#result_categories');
					
					for (var catI = 0, catC = data['categories'].length; catI < catC; catI++)
					{
						var catId = catI;
						var category = data['categories'][catI];
						
						catNode = catTemplate[0].cloneNode(true);
						catNode.id = null;
						catNode.innerHTML = category;
						catNode.style.display = '';
						
						resultCategoriesNode[0].appendChild(catNode);
						
						if (catId < data['categories'].length - 1)
						{
							resultCategoriesNode.append(', ');
						}
					}
				}
				else
				{
					template.find('#result_categories').remove();						
				}

				// tags
				if
				(
					data['tags']
						&& typeof(data['tags']) == 'object'
						&& data['tags'].length > 0
						&& (data['tags'].length != 1 || data['tags'][0] != '')
				)
				{
					var tagNode,
						tagTemplate = template.find('#result_tag_template'),
						resultTagsNode = template.find('#result_tags');
					
					for (var tagI = 0, tagC = data['tags'].length; tagI < tagC; tagI++)
					{
						var tagId = tagI;
						var tag = data['tags'][tagI];
						
						tagNode = tagTemplate[0].cloneNode(true);
						tagNode.id = null;
						tagNode.innerHTML = tag;
						tagNode.style.display = '';
						
						resultTagsNode[0].appendChild(tagNode);
						
						if (tagId < data['tags'].length - 1)
						{
							resultTagsNode.append(', ');
						}
					}
				}
				else
				{
					template.find('#result_tags').remove();						
				}
				
				// distance
				if (!data['distance'])
				{
					template.find('#result_distance_box').remove();
				}

				template = thisObj.fillTemplate(template, data, data['geo_latitude'] && data['geo_longitude']);
				thisObj.resultsCargo[0].appendChild(template[0]);
				thisObj.attachEventHandler(template, data['user'], userTranslations);

				if (data['geo_latitude'] && data['geo_longitude'])
				{
					thisObj.attachToGMResultList
					(
						data,
						template,
						"resultsLayerElement.requestOffer(this, '" + data['user']['userID'] + "', '" + userTranslations['REQUEST_OFFER_INFO'] + "', '" + userTranslations['REQUEST_OFFER_INFO_NOTICE'] + "', '" + userTranslations['REQUEST_OFFER_NO_OFFER_INFO'] + "', '" + userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE'] + "')",
						"resultsLayerElement.requestContactData(this, '" + data['user']['userID'] + "')"
					);
				}

				template.find('#markerBubble_template').remove();
			}
						
			this.initializeMap();
			
			if (result.resultdata.length == 0)
			{
				map.setCenter(new GLatLng(defaultMapCenter.lat, defaultMapCenter.lan), defaultMapCenter.zoom);
			}

			var centerWrapperObject = $('#center-wrapper'),
				gmScrollerHeight = $('#gmscroller').height();

			if (centerWrapperObject.height() < gmScrollerHeight)
			{
				centerWrapperObject.height(gmScrollerHeight + 'px');
			}
			else
			{
				centerWrapperObject.height('auto');
			}
		},
		
		buildUserTranslations: function (userData)
		{
			var userTranslations =
			{
				APPOINTMENT_HEADLINE: APPOINTMENT_HEADLINE_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                APPOINTMENT_INFO: APPOINTMENT_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                APPOINTMENT_DEFAULT_TEXT: APPOINTMENT_DEFAULT_TEXT_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                REQUEST_OFFER_INFO: REQUEST_OFFER_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                REQUEST_OFFER_INFO_NOTICE: REQUEST_OFFER_INFO_NOTICE_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                REQUEST_OFFER_NO_OFFER_INFO: REQUEST_OFFER_NO_OFFER_INFO_TPL.replace(/##CONTACTTITLE##/g, userData['username']),
                REQUEST_OFFER_NO_OFFER_INFO_NOTICE: REQUEST_OFFER_NO_OFFER_INFO_NOTICE_TPL.replace(/##CONTACTTITLE##/g, userData['username'])
			};
			
			return (userTranslations);			
		},
		
		attachEventHandler: function (template, userData, userTranslations)
		{
			if (!bAnonymousVisitor)
			{
				template.find('#make_appointment_link').click
				(
					function ()
					{
						resultsLayerElement.makeAppointment
						(
							this,
							userData['userID'],
							userTranslations['APPOINTMENT_HEADLINE'],
							userTranslations['APPOINTMENT_INFO'],
							userTranslations['APPOINTMENT_DEFAULT_TEXT']
						);
					}
				);

				template.find('#request_offer_link1').click
				(
					function ()
					{
						resultsLayerElement.requestOffer
						(
							this,
							userData['userID'],
							userTranslations['REQUEST_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_INFO_NOTICE'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE']
						);
					}
				);
	
				template.find('#request_offer_link2').click
				(
					function ()
					{
						resultsLayerElement.requestOffer
						(
							this,
							userData['userID'],
							userTranslations['REQUEST_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_INFO_NOTICE'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO'],
							userTranslations['REQUEST_OFFER_NO_OFFER_INFO_NOTICE']
						);
					}
				);
			}
			
			template.find('#request_contact_data_link').click
			(
				function ()
				{
					resultsLayerElement.requestContactData
					(
						this,
						userData['userID']
					);
				}
			);

			template.mouseover
			(
				function ()
				{
					GMInfoWindow(this.myId);
				}
			);
		},
		
		resetMap: function ()
		{
			active_marker_idx = -1
			map.clearOverlays();
			GMResultList = {};
		},
		
		initializeMap: function ()
		{
			initializeMap();
		},
		
		attachToGMResultList: function (result, template, requestOfferOnclickJs, requestContactOnclickJs)
		{
			GMResultList[result.hit] =
			{
				longitude: result['geo_longitude'],
				latitude: result['geo_latitude'],
				markerimage: result['hit_pin_url'],
				html: template.find('#markerBubble_template')[0].cloneNode(true),
				requestOfferOnclick: requestOfferOnclickJs,
				requestContactOnclick: requestContactOnclickJs
			};
		},
		
		renderPager: function (result)
		{
			var jObj = this.getJObject(),
				pagerPages = jObj.find('#pager_pages'),
				pageTemplate = $('#pager_page_template'),
				resultPageCurrent = parseInt(result['page_current']),
				resultPagePerpage = parseInt(result['page_perpage']),
				resultTotalResults = parseInt(result['total_results']),
				startPage = resultPageCurrent >= 5 ? resultPageCurrent - 4 : 1,
				endPage = Math.ceil(resultTotalResults / resultPagePerpage) - resultPageCurrent >= 5 ? resultPageCurrent + 4 : Math.ceil(resultTotalResults / resultPagePerpage),
				firstShownResult = (resultPageCurrent - 1) * resultPagePerpage + 1,
				lastShownResult = (resultPageCurrent - 1) * resultPagePerpage + result['resultdata'].length;
			
			if (resultTotalResults == 0)
			{
				firstShownResult = 0;
				lastShownResult = 0;
				
			}
			
			jObj.find('#pager_first_result_upper').html(String(firstShownResult));
			jObj.find('#pager_last_result_upper').html(String(lastShownResult));
			jObj.find('#pager_total_results_upper').html(String(resultTotalResults));

			jObj.find('#pager_first_result_lower').html(String(firstShownResult));
			jObj.find('#pager_last_result_lower').html(String(lastShownResult));
			jObj.find('#pager_total_results_lower').html(String(resultTotalResults));
			
			pagerPages.empty();
			
			if (startPage > 1)
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');
				page.addClass('results-page');
				page.html('<a href="javascript:redPages.fetchSearchResults(' + (startPage - 5 > 1 ? startPage - 5 : 1) + ');">&lt;&lt;</a> ');

				pagerPages.append(page);
			}

			for (var i = startPage; i <= endPage; i++)
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');
				
				if (resultPageCurrent == i)
				{
					page.addClass('results-active-page');
					page.html(i + ' ');
				}
				else
				{
					page.addClass('results-page');
					page.html('<a href="javascript:redPages.fetchSearchResults(' + i + ');">' + i + '</a> ');
				}
				
				pagerPages.append(page);
			}
			
			if (endPage < Math.ceil(resultTotalResults / resultPagePerpage))
			{
				var page = pageTemplate.clone(true);
				page.removeAttr('id');
				page.addClass('results-page');
				page.html('<a href="javascript:redPages.fetchSearchResults(' + (endPage + 5 < Math.ceil(resultTotalResults / resultPagePerpage) ? endPage + 5 : Math.ceil(resultTotalResults / resultPagePerpage)) + ');">&gt;&gt;</a>');

				pagerPages.append(page);
			}
		},
		
		fillTemplate: function (template, data, hasLocation, prefix)
		{
			var thisObj = this;
			
			prefix = prefix ? prefix : '';
			
			jQuery.each
			(
				data,
				function (id, value)
				{
					if (value && typeof(value) == 'object')
					{
						template = thisObj.fillTemplate(template, value, hasLocation, prefix + id + '\\.');
					}
					else
					{
						if (jQuery.trim(String(value)).length > 0)
						{
							var resultNode = template.find('#result_' + prefix + id)[0];
							var resultNodeContainer = template.find('#result_' + prefix + id + '_container')[0];
							
							if (resultNode)
							{
								resultNode.innerHTML = value;
								resultNode.style.display = '';
							}
							
							if (resultNodeContainer)
							{
								resultNodeContainer.style.display = '';
							}

							//template.find('#result_' + prefix + id).show().html(value);
							//template.find('#result_' + prefix + id + '_container').show();
						
							if (hasLocation)
							{		
								var markerBubbleNode = template.find('#markerBubble_result_' + prefix + id)[0];
								var markerBubbleNodeContainer = template.find('#markerBubble_result_' + prefix + id + '_container')[0];
								
								if (markerBubbleNode)
								{
									markerBubbleNode.innerHTML = value;
									markerBubbleNode.style.display = '';
								}	
									
								if (markerBubbleNodeContainer)
								{
									markerBubbleNodeContainer.style.display = '';
								}

								//template.find('#markerBubble_result_' + prefix + id).show().html(value);
								//template.find('#markerBubble_result_' + prefix + id + '_container').show();
							}
						}
					}
				}
			);
			
			return (template);
		}
	}
);


var resultsLayerElement = $.klass
(
	{
		initialize: function ()
		{
		},
		
		fetchData: function (type, userID, profileId, object, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();
				var feedName = 'inline-base';
				
				switch (type)
				{
					case 'makeAppointment':
					
						parameters.method = 'send-appointment';
						parameters.message = object.find('#makeAppointmentText').val();
						parameters.userID = userID;
						break;
						
					case 'requestOffer':

						parameters.method = 'send-offer';
						parameters.auctionID  = object.find('#requestOffer').val();
						parameters.message  = object.find('#requestOfferBody').val();
						parameters.profileId = profileId;
						parameters.listingReason = 'RequestQuote';
						parameters.omniturePagename = $('#omnPagename').html();
						parameters.eVar42 = 'BB-CompanyList_RequestQuote';
						break;

					case 'requestOfferWithoutJob':

						parameters.method = 'send-offer';
						parameters.profileId = profileId;
						parameters.listingReason = 'RequestQuote';
						parameters.omniturePagename = $('#omnPagename').html();
						parameters.eVar42 = 'BB-CompanyList_RequestQuote';
						break;

					case 'requestContactData':
					
						parameters.method = 'requestContactDetails';
						parameters.profileId = profileId;
						$('#contactDataRequestInfoLayer').css("top", ($(object).offset().top + 15) + "px");
						$('#contactDataRequestInfoLayer').css("left", ($(object).offset().left - 100) + "px");
						$('#contactDataRequestInfoLayer').appendTo(document.body);
						$('#contactDataRequestInfoLayer').show();
						break;
					
					default:
						break;
				}
				
				$.get
				(
					"/v3/profile-extended/ajax/" + feedName + ".php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(type, userID, profileId, object, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.sendto)
				{
					window.location.href = response.sendto;
					return;
				}

				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(this.watchedElement.domNode, response.error);
					}
					else if (response.errorlist)
					{
						jQuery.each
						(
							response.errorlist,
							function(fieldName, error)
							{
								showErrorBubble($('#' + thisObj.getErrorTarget(fieldName))[0], error);
							} 
						);
					}
					return (false);
				}
				else
				{
					switch (type)
					{
						case 'makeAppointment':
						case 'requestOffer':
						
							this.closeLayer(object);
							break;
							
						case 'requestContactData':

							$(object).hide();
							$(object).prev('.requestContactDataDisabled').show();
							break;
							
						default:
							break;
					}
				}
			}
		},
		
		requestContactData: function (button, profileId)
		{
			this.fetchData('requestContactData', null, profileId, $(button));
		},
		
		requestOffer: function (button, profileId, info, infoNotice, noInfo, noInfoNotice)
		{
			var templateNode;
			var thisObj = this;
			
			if (templateNode = $('#requestOfferLayer'))
			{
				var requestOfferObject = templateNode.clone(true);
				
				requestOfferObject.find('#requestOfferInfo').html(info);
				requestOfferObject.find('#requestOfferInfoNotice').html(infoNotice);
				requestOfferObject.find('#requestOfferNoInfo').html(noInfo);		
				requestOfferObject.find('#requestOfferNoInfoNotice').html(noInfoNotice);	
				requestOfferObject.find('#closeRequestOfferLayerButton').click
				(
					function ()
					{
						thisObj.closeLayer(requestOfferObject);
					}
				);
				requestOfferObject.find('#sendRequestOfferButton').click
				(
					function ()
					{
						thisObj.fetchData('requestOffer', null, profileId, requestOfferObject);
					}
				);
				
				document.body.appendChild(requestOfferObject[0]);
				
				var buttonOffsets = $(button).offset();
				requestOfferObject.css("left", buttonOffsets.left);
				requestOfferObject.css("top", buttonOffsets.top);
				
				requestOfferObject.fadeIn('slow', function() {
					// Focus Dropdown if more than one option available
					if (requestOfferObject.find('#requestOffer option').size() > 2) {
						requestOfferObject.find('#requestOffer').focus();
					} else {
						requestOfferObject.find('#requestOfferBody').focus();
					}
				});
				
			}
		},

		requestOfferWithoutJob: function (profileId) {
			var thisObj = this;
			thisObj.fetchData('requestOfferWithoutJob', null, profileId);
		},

		makeAppointment: function (button, userID, headline, info, text)
		{
			var templateNode;
			var thisObj = this;
			
			if (templateNode = $('#makeAppointmentLayer'))
			{
				var appointmentObject = templateNode.clone(true);
				
				appointmentObject.find('#makeAppointmentHeadline').html(headline);
				appointmentObject.find('#makeAppointmentInfo').html(info);
				appointmentObject.find('#makeAppointmentText').html(text);		
				appointmentObject.find('#closeAppointmentLayerButton').click
				(
					function ()
					{
						thisObj.closeLayer(appointmentObject);
					}
				);
				appointmentObject.find('#appointmentSendButton').click
				(
					function ()
					{
						thisObj.fetchData('makeAppointment', userID, null, appointmentObject);
					}
				);
				
				document.body.appendChild(appointmentObject[0]);
				
				var buttonOffsets = $(button).offset();
				appointmentObject.css("left", buttonOffsets.left);
				appointmentObject.css("top", buttonOffsets.top);
				
				appointmentObject.fadeIn('slow');
			}
		},
		
		closeLayer: function (layer)
		{
			layer.fadeOut('slow');
			
			window.setTimeout
			(
				function ()
				{
					layer.remove();
				},
				1000
			);	
		}
	}
);

function showErrorBubble (element, content, isSuccessBubble, leftOffset, topOffset)
{
	var templateNode,
		templateType;

    if (!topOffset) {
        topOffset = 0;
    }

    if (!leftOffset) {
        leftOffset = 0;
    }
	
	if (isSuccessBubble)
	{
		templateType = 'successBubble';
	}
	else
	{
		templateType = 'errorBubble';
	}
			
	if (templateNode = $('#' + templateType))
	{
		var errorBubbleDomNode = templateNode.clone(true);
		errorBubbleDomNode.removeAttr('id');
		
		if (content)
		{
			var bubbleContent = errorBubbleDomNode.find('#errorBubbleContent');
			bubbleContent.html(content);
		}

		$(document.body).append(errorBubbleDomNode);

		var elementOffsets = $(element).offset();
		var elementHeight = $(element).height();
		
		errorBubbleDomNode.css("left", (elementOffsets.left + 10 + leftOffset));
		errorBubbleDomNode.css("top", (elementOffsets.top + (elementHeight / 2) - 27) + topOffset);
		
		errorBubbleDomNode.click
		(
			function ()
			{
				hideErrorBubble(errorBubbleDomNode);
			}
		);

		window.setTimeout
		(
			function ()
			{
				hideErrorBubble(errorBubbleDomNode)
			},
			5000
		);

	}
}

function hideErrorBubble (bubble)
{
	bubble.remove();
}

function starPicUrl(score)
{
	var starpics = new Array();
	starpics[0.0] = 'http://f.myhcdn.net/v3/live/icons/00starYellowNew.gif';
    starpics[0.5] = 'http://a.myhcdn.net/v3/live/icons/05starYellowNew.gif';
    starpics[1.0] = 'http://f.myhcdn.net/v3/live/icons/10starYellowNew.gif';
    starpics[1.5] = 'http://c.myhcdn.net/v3/live/icons/15starYellowNew.gif';
    starpics[2.0] = 'http://b.myhcdn.net/v3/live/icons/20starYellowNew.gif';
    starpics[2.5] = 'http://f.myhcdn.net/v3/live/icons/25starYellowNew.gif';
    starpics[3.0] = 'http://c.myhcdn.net/v3/live/icons/30starYellowNew.gif';
    starpics[3.5] = 'http://d.myhcdn.net/v3/live/icons/35starYellowNew.gif';
    starpics[4.0] = 'http://d.myhcdn.net/v3/live/icons/40starYellowNew.gif';
    starpics[4.5] = 'http://a.myhcdn.net/v3/live/icons/45starYellowNew.gif';
    starpics[5.0] = 'http://c.myhcdn.net/v3/live/icons/50starYellowNew.gif';
    starpics[5.5] = 'http://c.myhcdn.net/v3/live/icons/50starYellowNew.gif';
    starpics[6.0] = 'http://f.myhcdn.net/v3/live/icons/60starYellowNew.gif';
    
    return starpics[score];
}

function formatDate(t)
{
	var date = new Date();
	
	if (t != 'now')
	{
		date.setTime((t < 9999999999) ? t * 1000 : t);
	}
	
	var d = date.getDate();
	var m = date.getMonth() + 1;
	var y = date.getFullYear();
	return (d < 10 ? '0' : '') + d + '.' + (m < 10 ? '0' : '') + m + '.' + y;
}

function getSMPScriptPrefix()
{
	return('/v3');
}

var adsenseCurrent = 0;
var adsenseContainer = new Array();
var adsenseTracking = new Array();
var adsenseLineSeperator = new Array();

function google_ad_request_done(google_ads)
{
	adsenseCurrent++;
	
	var tracking = "";
	if (typeof adsenseTracking[adsenseCurrent-1] != "undefined") {
		if (adsenseTracking[adsenseCurrent-1] != "") {
			var tracking = 'onclick="s_objectID=\'' + adsenseTracking[adsenseCurrent-1] + '\'" ';
		} 
	}
	
	if (google_ads.length == 0 || adsenseCurrent > adsenseContainer.length || adsenseCurrent > adsenseLineSeperator.length)
	{
		return;
	}

	var content = '';


	if (google_ads[0].type == "flash")
	{
		content = '<div class="goggleLink" style="width: ' + google_ads[0].image_width + 'px;">' +
		          ' <a href="' + google_info.feedback_url + '" target="_blank">Ads by Google</a>' +
		          '</div>' +
		          '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' + google_ad.image_width + '" height="' + google_ad.image_height + '"' +
		          ' <param name="movie" value="' + google_ad.image_url + '">' +
		          ' <param name="quality" value="high">' +
				  ' <param name="wmode" value="transparent">' +
		          ' <param name="AllowScriptAccess" value="never">' +
		          ' <embed src="' + google_ad.image_url + '" width="' + google_ad.image_width + '" height="' + google_ad.image_height + '" type="application/x-shockwave-flash" AllowScriptAccess="never" wmode="transparent" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></embed>' +
		          '</object>';
	}
	else if (google_ads[0].type == "image")
	{
		content = '<div>' +
		          ' <div class="goggleLink" style="width: ' + google_ads[0].image_width + 'px;">' +
		          '  <a href="' + google_info.feedback_url + '" target="_blank">Ads by Google</a>' +
		          ' </div>' +
		          ' <a ' + tracking + ' href="' + google_ads[0].url + '" target="_blank" title="go to ' + google_ads[0].visible_url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\';return true">' + 
		          '  <img border="0" src="' + google_ads[0].image_url + '" width="' + google_ads[0].image_width + '" height="' + google_ads[0].image_height + '" />' +
		          ' </a>' +
		          '</div><br />';
	}
	else if (google_ads[0].type == "html")
	{
		content = google_ads[0].snippet;
	}
	else
	{
		content = '<div class="adsense">' +
		          '<div class="goggleLink"><a href="' + google_info.feedback_url + '\" target="_blank">Ads by Google</a></div>' +
		          '<ul>';
	
		for (var i = 0; i < google_ads.length; i++)
		{
			content += '<li>' +
			           ' <a ' + tracking + ' href="' + google_ads[i].url + '" target="_blank" style="text-decoration: none" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\';return true">' +
			           '  <span style="text-decoration:underline"><b>' + google_ads[i].line1 + '</b></span>' +
			           ' </a><br />' +
			           ' <span style="color: #000">' +
			           '  ' + google_ads[i].line2 + adsenseLineSeperator[adsenseCurrent-1] +
			           '  ' + google_ads[i].line3 + '<br />' +
			           ' </span>' +
			           ' <a ' + tracking + ' href="' + google_ads[i].url + '" target="_blank" style="color: #008000; text-decoration: none" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\';return true">' +
			           '  ' + google_ads[i].visible_url +
			           ' </a>' +
			           '</li>';
		}
		
		content += '</ul>' +
		           '<div style="clear: both; height: 1px;"></div>' +
		           '</div>';
	}
	
	var obj = document.getElementById(adsenseContainer[adsenseCurrent-1]);
	if (obj) obj.innerHTML = content;
}


var sDirectorySearchTypeCookieName = 'searchType';

$().ready(function() {
	$('a[class*=search-type-]').click(function() {
		directorySearchTypeClick(this);
	});
});

function directorySearchTypeClick(obj) {
	var aClasses = $(obj).attr('class').split(' ');
	var sSearchType = '';
	var sSearchTerm = '';
	for (var i = 0; i < aClasses.length; i++) {
		if (aClasses[i].substr(0, 12) == 'search-type-') {
			sSearchType = aClasses[i].substr(12);
			sSearchTerm = $(obj).html();
			break;
		}
	}
	if (sSearchType != '') {
		setCookie(sDirectorySearchTypeCookieName, sSearchType + '|' + sSearchTerm, 250, '/', getCookieDomain(), false);
	}
}


/**
 * sets the product finding method cookie
 * @param sValue
 */
function setProductFindingMethod(sValue) {
	if(sValue && sValue != '') {
		setCookie('omnitureProductFindingMethod', sValue, 0, '/', getCookieDomain());
	}
}

function OmTransporter() {
}
OmTransporter.cookieName = 'omTransporter';

OmTransporter.setVar = function(sName, sValue) {
	var aParameters = OmTransporter.getAll();
	var bIsSet = false;
	for (var i = 0; i < aParameters.length; i++) {
		if (aParameters[i].name == sName) {
			aParameters[i].value = sValue;
			bIsSet = true;
		}
	}
	if(!bIsSet) {
		aParameters.push(new OmnitureParameter(sName, sValue));
	}
	OmTransporter.setAll(aParameters);
};

OmTransporter.getAll = function() {
	var sValueComplete = getCookie(OmTransporter.cookieName);
	if (sValueComplete != null) {
		var aKeyValues = sValueComplete.split(';');
		var aKeyValue;
		var aoParameters = new Array();
		for (var i = 0; i < aKeyValues.length; i++) {
			aKeyValue = aKeyValues[i].split(':');
			aoParameters.push(new OmnitureParameter(aKeyValue[0], aKeyValue[1]));
		}
		return aoParameters;
	}
	return new Array();
};

OmTransporter.setAll = function(aoParameters) {
	var aKeyValues = new Array();
	for (var i = 0; i < aoParameters.length; i++) {
		aKeyValues[i] = aoParameters[i].name + ':' + aoParameters[i].value;
	}

	var sKeyValues = aKeyValues.join(';');
	setCookie(OmTransporter.cookieName, sKeyValues, 0, '/', getCookieDomain());
};


/**
* Omniture Parameter
* @param string sName
* @param string sValue
*/
function OmnitureParameter(sName, sValue)
{
	this.name = sName;
	this.value = sValue;
}

/**
* Omniture Tracking Class
* 
* @param object oLinkArgument The Link object that should be tracked (if this is called in a onclick event, simply set it to 'this')
* @param string sLinkTitleArgument The Linkname (if not set Omniture takes it from oLinkArgument)
*/
function Omniture(oLinkArgument, sLinkTitleArgument) {
	this.oLink = false;
	this.sTitle;
	this.eLinkType = 'o';
	
	if(typeof(oLinkArgument) != 'undefined') {
		this.oLink = oLinkArgument;
	}
	
	if(typeof(sLinkTitleArgument) != 'undefined') {
		this.sTitle = sLinkTitleArgument;
	}
}

/**
* Is the data send? Use bForceSending in sencCall() to force sending
* @static
*/
Omniture.dataSend = false;

/**
* send the data to omniture. to overwrite existing parameters or add additional set an array containing a object for each parameter
* eg: new Array(
*		new OmnitureParameter('prop16', 'value for prop16'),
*		new OmnitureParameter('prop14', 'usefull value for prop14')
*	)
* @param aParameter array of OmnitureParameters
* @param bForceSending Set to true to send the call if it was allready send on this page
*/
Omniture.prototype.sendCall = function(aParameter, bForceSending)
{
	if(typeof(bForceSending) == 'undefined') {
		bForceSending = false;
	}
	
	if(Omniture.dataSend == false || bForceSending == true)
	{
		var aParameterNames = new Array();
		var aTempEvents = new Array();
		var s = s_gi(s_account);

		for(var i = 0; i < aParameter.length; i++)
		{
			var aParameterPair = aParameter[i];
			if(aParameterPair.name == 'events') {
				aTempEvents[aTempEvents.length] = aParameterPair.value;
			} else {
				s[aParameterPair.name] = aParameterPair.value;
			}
			aParameterNames[aParameterNames.length] = aParameterPair.name;
		}
		
		s.linkTrackVars = aParameterNames.join(',');
		if(aTempEvents.length > 0) {
			s.linkTrackEvents = aTempEvents.join(',');
			s.events = aTempEvents.join(',');
			//s.linkTrackVars += ',events';
		}
		
		s.tl(this.oLink, 'o', this.sTitle);
		Omniture.dataSend = true;		
	}
};

Omniture.send = function(aParams) {
	aOmnitureParameters = [];

	$.each(aParams, function(paramName, value) {
		aOmnitureParameters.push(new OmnitureParameter(paramName, value));
	});

	var oOmniture = new Omniture();
	oOmniture.sendCall(aOmnitureParameters, true);
};

/*
 * nyroModal - jQuery Plugin
 * http://nyromodal.nyrodev.com
 *
 * Copyright (c) 2008 Cedric Nirousset (nyrodev.com)
 * Licensed under the MIT license
 *
 * $Date: 2009-10-19 18:57:30 +0200 (Mon, 19 Oct 2009) $
 * $version: 1.3.1
 */
jQuery(function($) {

	// -------------------------------------------------------
	// Private Variables
	// -------------------------------------------------------

	var isIE6 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7);
	var body = $('body');

	var currentSettings;

	// To know if the fix for the Issue 10 should be applied (or has been applied)
	var fixFF = false;

	// Used for retrieve the content from an hidden div
	var contentElt;
	var contentEltLast;

	// Contains info about nyroModal state and all div references
	var modal = {
		started: false,
		ready: false,
		dataReady: false,
		anim: false,
		loadingShown: false,
		transition: false,
		error: false,
		full: null,
		bg: null,
		loading: null,
		tmp: null,
		content: null,
		wrapper: null,
		closing: false,
		contentWrapper: null,
		scripts: new Array()
	};

	// Indicate of the height or the width was resized, to reinit the currentsettings related to null
	var resized = {
		width: false,
		height: false
	};


	// -------------------------------------------------------
	// Public function
	// -------------------------------------------------------

	// jQuery extension function. A paramater object could be used to overwrite the default settings
	$.fn.nyroModal = function(settings) {
		if (!this)
			return false;
		return this.each(function(){
			if (this.nodeName.toLowerCase() == 'form') {
				$(this).submit(function(e) {
					if (this.enctype == 'multipart/form-data') {
						processModal($.extend(settings, {
							from: this
						}));
						return true;
					}
					e.preventDefault();
					processModal($.extend(settings, {
						from: this
					}));
					return false;
				});
			} else {
				$(this).click(function(e) {
					e.preventDefault();
					processModal($.extend(settings, {
						from: this
					}));
					return false;
				});
			}
		});
	};

	// jQuery extension function to call manually the modal. A paramater object could be used to overwrite the default settings
	$.fn.nyroModalManual = function(settings) {
		if (!this.length)
			processModal(settings);
		return this.each(function(){
			processModal($.extend(settings, {
				from: this
			}));
		});
	};

	$.nyroModalManual = function(settings) {
		processModal(settings);
	};

	// Update the current settings
	// object settings
	// string deep1 first key where overwrite the settings
	// string deep2 second key where overwrite the settings
	$.nyroModalSettings = function(settings, deep1, deep2) {
		setCurrentSettings(settings, deep1, deep2);
		if (!deep1 && modal.started) {
			if (modal.bg && settings.bgColor)
				currentSettings.updateBgColor(modal, currentSettings, function(){});

			if (modal.contentWrapper && settings.title) {
				title = $('h1#nyroModalTitle', modal.contentWrapper);
				if (title.length)
					title.text(settings.title);
				else
					modal.contentWrapper.prepend('<h1 id="nyroModalTitle">'+settings.title+'</h1>');
			}

			if (modal.content && (modal.dataReady && !modal.anim && !modal.transition) && (settings.width || settings.height)) {
				calculateSize(true);

				if (fixFF)
					modal.content.css({position: ''});
				currentSettings.resize(modal, currentSettings, function() {
					if (fixFF)
						modal.content.css({position: 'fixed'});
					if ($.isFunction(currentSettings.endResize))
						currentSettings.endResize(modal, currentSettings);
				});
			}
		}
	};

	// Remove the modal function
	$.nyroModalRemove = function() {
		removeModal();
	};

	// Go to the next image for a gallery
	// return false if nothing was done
	$.nyroModalNext = function() {
		var link = getGalleryLink(1);
		if (link)
			return link.nyroModalManual(currentSettings);
		return false;
	};

	// Go to the previous image for a gallery
	// return false if nothing was done
	$.nyroModalPrev = function() {
		var link = getGalleryLink(-1);
		if (link)
			return link.nyroModalManual(currentSettings);
		return false;
	};


	// -------------------------------------------------------
	// Default Settings
	// -------------------------------------------------------

	$.fn.nyroModal.settings = {
		debug: false, // Show the debug in the background

		modal: false, // Esc key or click backgrdound enabling or not

		type: '', // nyroModal type (form, formData, iframe, image, etc...)
		from: '', // Dom object where the call come from
		hash: '', // Eventual hash in the url

		processHandler: null, // Handler just before the real process

		selIndicator: 'nyroModalSel', // Value added when a form or Ajax is sent with a filter content

		formIndicator: 'nyroModal', // Value added when a form is sent

		content: null, // Raw content if type content is used

		bgColor: '#000000', // Background color

		ajax: {}, // Ajax option (url, data, type, success will be overwritten for a form, url and success only for an ajax call)

		swf: { // Swf player options if swf type is used.
			wmode: 'transparent'
		},

		width: null, // default Width If null, will be calculate automatically
		height: null, // default Height If null, will be calculate automatically

		minWidth: 400, // Minimum width
		minHeight: 300, // Minimum height

		resizable: true, // Indicate if the content is resizable. Will be set to false for swf
		autoSizable: true, // Indicate if the content is auto sizable. If not, the min size will be used

		padding: 25, // padding for the max modal size

		regexImg: '[^\.]\.(jpg|jpeg|png|tiff|gif|bmp)\s*$', // Regex to find images
		defaultImgAlt: 'Image', // Default alt attribute for the images
		setWidthImgTitle: true, // Set the width to the image title
		ltr: true, // Left to Right by default. Put to false for Hebrew or Right to Left language

		css: { // Default CSS option for the nyroModal Div. Some will be overwritten or updated when using IE6
			bg: {
				zIndex: 100,
				position: 'fixed',
				top: 0,
				left: 0,
				height: '100%',
				width: '100%'
			},
			wrapper: {
				zIndex: 101,
				position: 'fixed',
				top: '50%',
				left: '50%'
			},
			wrapper2: {
			},
			content: {
				overflow: 'auto'
			},
			loading: {
				zIndex: 102,
				position: 'fixed',
				top: '50%',
				left: '50%',
				marginTop: '-50px',
				marginLeft: '-50px'
			}
		},

		wrap: { // Wrapper div used to style the modal regarding the content type
			div: '<div class="wrapper"></div>',
			ajax: '<div class="wrapper"></div>',
			form: '<div class="wrapper"></div>',
			formData: '<div class="wrapper"></div>',
			image: '<div class="wrapperImg"></div>',
			gallery: '<div class="wrapperImg"><a href="#" class="nyroModalPrev">Prev</a><a href="#"  class="nyroModalNext">Next</a></div>', // Use .nyroModalPrev and .nyroModalNext to set the navigation link
			swf: '<div class="wrapperSwf"></div>',
			iframe: '<div class="wrapperIframe"></div>',
			manual: '<div class="wrapper"></div>'
		},

		closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="close">Close</a>', // Adding automaticly as the first child of #nyroModalWrapper
		
		title: null, // Modal title
		titleFromIframe: true, // When using iframe in the same domain, try to get the title from it

		openSelector: '.nyroModal', // selector for open a new modal. will be used to parse automaticly at page loading
		closeSelector: '.nyroModalClose', // selector to close the modal

		contentLoading: '<a href="#" class="nyroModalClose">Cancel</a>', // Loading div content

		errorClass: 'error', // CSS Error class added to the loading div in case of error
		contentError: 'The requested content cannot be loaded.<br />Please try again later.<br /><a href="#" class="nyroModalClose">Close</a>', // Content placed in the loading div in case of error

		handleError: null, // Callback in case of error

		showBackground: showBackground, // Show background animation function
		hideBackground: hideBackground, // Hide background animation function

		endFillContent: null, // Will be called after filling and wraping the content, before parsing closeSelector and openSelector and showing the content
		showContent: showContent, // Show content animation function
		endShowContent: null, // Will be called once the content is shown
		beforeHideContent: null, // Will be called just before the modal closing
		hideContent: hideContent, // Hide content animation function

		showTransition: showTransition, // Show the transition animation (a modal is already shown and a new one is requested)
		hideTransition: hideTransition, // Hide the transition animation to show the content

		showLoading: showLoading, // show loading animation function
		hideLoading: hideLoading, // hide loading animation function

		resize: resize, // Resize animation function
		endResize: null, // Will be called one the content is resized

		updateBgColor: updateBgColor, // Change background color animation function

		endRemove: null // Will be called once the modal is totally gone
	};


	// -------------------------------------------------------
	// Private function
	// -------------------------------------------------------

	// Main function
	function processModal(settings) {
		if (modal.loadingShown || modal.transition || modal.anim)
			return;
		debug('processModal');
		modal.started = true;
		setDefaultCurrentSettings(settings);
		modal.error = false;
		modal.closing = false;
		modal.dataReady = false;
		modal.scripts = new Array();

		currentSettings.type = fileType();

		if ($.isFunction(currentSettings.processHandler))
			currentSettings.processHandler(currentSettings);

		from = currentSettings.from;
		url = currentSettings.url;

		if (currentSettings.type == 'swf') {
			// Swf is transforming as a raw content
			currentSettings.resizable = false;
			setCurrentSettings({overflow: 'hidden'}, 'css', 'content');
			currentSettings.content = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+currentSettings.width+'" height="'+currentSettings.height+'"><param name="movie" value="'+url+'"></param>';
			var tmp = '';
			$.each(currentSettings.swf, function(name, val) {
				currentSettings.content+= '<param name="'+name+'" value="'+val+'"></param>';
				tmp+= ' '+name+'="'+val+'"';
			});
			currentSettings.content+= '<embed src="'+url+'" type="application/x-shockwave-flash" width="'+currentSettings.width+'" height="'+currentSettings.height+'"'+tmp+'></embed></object>';
		}

		if (from) {
			var jFrom = $(from);
			if (currentSettings.type == 'form') {
				var data = $(from).serializeArray();
				data.push({name: currentSettings.formIndicator, value: 1});
				if (currentSettings.selector)
					data.push({name: currentSettings.selIndicator, value: currentSettings.selector.substring(1)});
				$.ajax($.extend({}, currentSettings.ajax, {
						url: url,
						data: data,
						type: from.method,
						success: ajaxLoaded,
						error: loadingError
					}));
				debug('Form Ajax Load: '+jFrom.attr('action'));
				showModal();
			} else if (currentSettings.type == 'formData') {
				// Form with data. We're using a hidden iframe
				initModal();
				jFrom.attr('target', 'nyroModalIframe');
				jFrom.attr('action', url);
				jFrom.prepend('<input type="hidden" name="'+currentSettings.formIndicator+'" value="1" />');
				if (currentSettings.selector)
					jFrom.prepend('<input type="hidden" name="'+currentSettings.selIndicator+'" value="'+currentSettings.selector.substring(1)+'" />');
				modal.tmp.html('<iframe frameborder="0" hspace="0" name="nyroModalIframe"></iframe>');
				$('iframe', modal.tmp)
					.css({
						width: currentSettings.width,
						height: currentSettings.height
					})
					.error(loadingError)
					.load(formDataLoaded);
				debug('Form Data Load: '+jFrom.attr('action'));
				showModal();
				showContentOrLoading();
			} else if (currentSettings.type == 'image' || currentSettings.type == 'gallery') {
				var title = jFrom.attr('title') || currentSettings.defaultImgAlt;
				initModal();
				modal.tmp.html('<img id="nyroModalImg" />').find('img').attr('alt', title);
				debug('Image Load: '+url);
				modal.tmp.css({lineHeight: 0});
				$('img', modal.tmp)
					.error(loadingError)
					.load(function() {
						debug('Image Loaded: '+this.src);
						$(this).unbind('load');
						var w = modal.tmp.width();
						var h = modal.tmp.height();
						modal.tmp.css({lineHeight: ''});
						setCurrentSettings({
							width: w,
							height: h,
							imgWidth: w,
							imgHeight: h
						});
						setCurrentSettings({overflow: 'hidden'}, 'css', 'content');
						modal.dataReady = true;
						if (modal.loadingShown || modal.transition)
							showContentOrLoading();
					})
					.attr('src', url);
				showModal();
			} else if (currentSettings.type == 'iframe') {
				initModal();
				modal.tmp.html('<iframe frameborder="0" hspace="0" src="'+url+'" name="nyroModalIframe"></iframe>');
				debug('Iframe Load: '+url);
				$('iframe', modal.tmp).eq(0)
					.css({
						width: '100%',
						height: isDoctypeStrict()? '99%' : '100%'
					})
					.load(function(e) {
						if (currentSettings.titleFromIframe && url.indexOf(window.location.hostname) > -1)
							$.nyroModalSettings({title: $('iframe', modal.full).contents().find('title').text()});
					});
				currentSettings.autoSizable = false;
				modal.dataReady = true;
				showModal();
			} else if (currentSettings.type) {
				// Could be every other kind of type or a dom selector
				debug('Content: '+currentSettings.type);
				initModal();
				modal.tmp.html(currentSettings.content);
				var w = modal.tmp.width();
				var h = modal.tmp.height();
				var div = $(currentSettings.type);
				if (div.length) {
					setCurrentSettings({type: 'div'});
					w = div.width();
					h = div.height();
					if (contentElt)
						contentEltLast = contentElt;
					contentElt = div;
					modal.tmp.append(div.contents());
				}
				setCurrentSettings({
					width: w,
					height: h
				});
				if (modal.tmp.html())
					modal.dataReady = true;
				else
					loadingError();
				showModal();
				showContentOrLoading();
			} else {
				debug('Ajax Load: '+url);
				setCurrentSettings({type: 'ajax'});
				var data = currentSettings.ajax.data || {};
				if (currentSettings.selector) {
					if (typeof data == "string") {
						data+= '&'+currentSettings.selIndicator+'='+currentSettings.selector.substring(1);
					} else {
						data[currentSettings.selIndicator] = currentSettings.selector.substring(1);
					}
				}
				$.ajax($.extend(true, currentSettings.ajax, {
					url: url,
					success: ajaxLoaded,
					error: loadingError,
					data: data
				}));
				showModal();
			}
		} else if (currentSettings.content) {
			// Raw content not from a DOM element
			debug('Content: '+currentSettings.type);
			setCurrentSettings({type: 'manual'});
			initModal();
			modal.tmp.html($('<div/>').html(currentSettings.content).contents());
			if (modal.tmp.html())
				modal.dataReady = true;
			else
				loadingError();
			showModal();
		} else {
			// What should we show here? nothing happen
		}
	}

	// Update the current settings
	// object settings
	// string deep1 first key where overwrite the settings
	// string deep2 second key where overwrite the settings
	function setDefaultCurrentSettings(settings) {
		debug('setDefaultCurrentSettings');
		currentSettings = $.extend({}, $.fn.nyroModal.settings, settings);
		currentSettings.selector = '';
		currentSettings.borderW = 0;
		currentSettings.borderH = 0;
		currentSettings.resizable = true;
		setMargin();
	}

	function setCurrentSettings(settings, deep1, deep2) {
		if (modal.started) {
			if (deep1 && deep2) {
				$.extend(currentSettings[deep1][deep2], settings);
			} else if (deep1) {
				$.extend(currentSettings[deep1], settings);
			} else {
				$.extend(currentSettings, settings);
			}
		} else {
			if (deep1 && deep2) {
				$.extend($.fn.nyroModal.settings[deep1][deep2], settings);
			} else if (deep1) {
				$.extend($.fn.nyroModal.settings[deep1], settings);
			} else {
				$.extend($.fn.nyroModal.settings, settings);
			}
		}
	}

	// Set the margin for postionning the element. Useful for IE6
	function setMarginScroll() {
		if (isIE6) {
			if (document.documentElement) {
				currentSettings.marginScrollLeft = document.documentElement.scrollLeft;
				currentSettings.marginScrollTop = document.documentElement.scrollTop;
			} else {
				currentSettings.marginScrollLeft = document.body.scrollLeft;
				currentSettings.marginScrollTop = document.body.scrollTop;
			}
		} else {
			currentSettings.marginScrollLeft = 0;
			currentSettings.marginScrollTop = 0;
		}
	}

	// Set the margin for the content
	function setMargin() {
		setMarginScroll();
		currentSettings.marginLeft = -(currentSettings.width+currentSettings.borderW)/2 + currentSettings.marginScrollLeft;
		currentSettings.marginTop = -(currentSettings.height+currentSettings.borderH)/2 + currentSettings.marginScrollTop;
	}

	// Set the margin for the current loading
	function setMarginloading() {
		setMarginScroll();
		var outer = getOuter(modal.loading);
		currentSettings.marginTopLoading = -(modal.loading.height() + outer.h.border + outer.h.padding)/2 + currentSettings.marginScrollTop;
		currentSettings.marginLeftLoading = -(modal.loading.width() + outer.w.border + outer.w.padding)/2 + currentSettings.marginScrollLeft;
	}

	// Init the nyroModal div by settings the CSS elements and hide needed elements
	function initModal() {
		debug('initModal');
		if (!modal.full) {
			if (currentSettings.debug)
				setCurrentSettings({color: 'white'}, 'css', 'bg');

			var iframeHideIE = '';
			if (isIE6) {
				body.css({
					height: body.height()+'px',
					width: body.width()+'px',
					position: 'static',
					overflow: 'hidden'
				});
				$('html').css({overflow: 'hidden'});
				setCurrentSettings({
					position: 'absolute',
					height: '110%',
					width: '110%',
					top: currentSettings.marginScrollTop+'px',
					left: currentSettings.marginScrollLeft+'px'
				}, 'css', 'bg');

				setCurrentSettings({position: 'absolute'}, 'css', 'loading');
				setCurrentSettings({position: 'absolute'}, 'css', 'wrapper');

				iframeHideIE = $('<iframe id="nyroModalIframeHideIe"></iframe>')
								.css($.extend({},
									currentSettings.css.bg, {
										opacity: 0,
										zIndex: 50,
										border: 'none'
									}));
			}

			body.append($('<div id="nyroModalFull"><div id="nyroModalBg"></div><div id="nyroModalWrapper"><div id="nyroModalContent"></div></div><div id="nyrModalTmp"></div><div id="nyroModalLoading"></div></div>').hide());

			modal.full = $('#nyroModalFull').show();
			modal.bg = $('#nyroModalBg')
				.css($.extend({
						backgroundColor: currentSettings.bgColor
					}, currentSettings.css.bg))
				.before(iframeHideIE);
			if (!currentSettings.modal)
				modal.bg.click(removeModal);
			modal.loading = $('#nyroModalLoading')
				.css(currentSettings.css.loading)
				.hide();
			modal.contentWrapper = $('#nyroModalWrapper')
				.css(currentSettings.css.wrapper)
				.hide();
			modal.content = $('#nyroModalContent');
			modal.tmp = $('#nyrModalTmp').hide();

			// To stop the mousewheel if the the plugin is available
			if ($.isFunction($.fn.mousewheel)) {
				modal.content.mousewheel(function(e, d) {
					var elt = modal.content.get(0);
					if ((d > 0 && elt.scrollTop == 0) ||
							(d < 0 && elt.scrollHeight - elt.scrollTop == elt.clientHeight)) {
						e.preventDefault();
						e.stopPropagation();
					}
				});
			}

			$(document).keydown(keyHandler);
			modal.content.css({width: 'auto', height: 'auto'});
			modal.contentWrapper.css({width: 'auto', height: 'auto'});
		}
	}

	// Show the modal (ie: the background and then the loading if needed or the content directly)
	function showModal() {
		debug('showModal');
		if (!modal.ready) {
			initModal();
			modal.anim = true;
			currentSettings.showBackground(modal, currentSettings, endBackground);
		} else {
			modal.anim = true;
			modal.transition = true;
			currentSettings.showTransition(modal, currentSettings, function(){endHideContent();modal.anim=false;showContentOrLoading();});
		}
	}

	// Used for the escape key or the arrow in the gallery type
	function keyHandler(e) {
		if (e.keyCode == 27) {
			if (!currentSettings.modal)
				removeModal();
		} else if (currentSettings.type == 'gallery' && modal.ready && modal.dataReady && !modal.anim && !modal.transition) {
			if (e.keyCode == 39 || e.keyCode == 40) {
				e.preventDefault();
				$('.nyroModalNext', modal.content).eq(0).trigger('click');
				return false;
			} else if (e.keyCode == 37 || e.keyCode == 38) {
				e.preventDefault();
				$('.nyroModalPrev', modal.content).eq(0).trigger('click');
				return false;
			}
		}
	}

	// Determine the filetype regarding the link DOM element
	function fileType() {
		if (currentSettings.forceType) {
			var tmp = currentSettings.forceType;
			if (!currentSettings.content)
				currentSettings.from = true;
			currentSettings.forceType = null;
			return tmp;
		}

		var from = currentSettings.from;

		var url;

		if (from && from.nodeName) {
			var jFrom = $(from);
			currentSettings.url = url = from.nodeName.toLowerCase() == 'form'? jFrom.attr('action') : from.href;

			if (jFrom.attr('rev') == 'modal')
				currentSettings.modal = true;

			if (jFrom.attr('title'))
				currentSettings.title = jFrom.attr('title');

			var imgType = imageType(url, from);
			if (imgType)
				return imgType;

			if (from.target && from.target.toLowerCase() == '_blank' || (from.hostname && from.hostname.replace(/:\d*$/,'') != window.location.hostname.replace(/:\d*$/,''))) {
				return 'iframe';
			} else if (from.nodeName.toLowerCase() == 'form') {
				setCurrentSettings(extractUrlSel(url));
				if (jFrom.attr('enctype') == 'multipart/form-data')
					return 'formData';
				return 'form';
			}
		} else {
			url = currentSettings.url;
			if (!currentSettings.content)
				currentSettings.from = true;

			if (!url)
				return null;

			var reg1 = new RegExp("^http://", "g");
			if (url.match(reg1))
				return 'iframe';
		}

		var imgType = imageType(url, from);
		if (imgType)
			return imgType;

		var swf = new RegExp('[^\.]\.(swf)\s*$', 'i');
		if (swf.test(url))
			return 'swf';

		var tmp = extractUrlSel(url);
		setCurrentSettings(tmp);

		if (!tmp.url)
			return tmp.selector;
	}

	function imageType(url, from) {
		var image = new RegExp(currentSettings.regexImg, 'i');
		if (image.test(url)) {
			if (from && from.rel)
				return 'gallery';
			else
				return 'image';
		}
	}

	function extractUrlSel(url) {
		var ret = {
			url: null,
			selector: null
		};

		if (url) {
			var hash = getHash(url);
			var hashLoc = getHash(window.location.href);
			var curLoc = window.location.href.substring(0, window.location.href.length - hashLoc.length);
			var req = url.substring(0, url.length - hash.length);

			if (req == curLoc) {
				ret.selector = hash;
			} else {
				ret.url = req;
				ret.selector = hash;
			}
		}
		return ret;
	}

	// Called when the content cannot be loaded or tiemout reached
	function loadingError() {
		debug('loadingError');

		modal.error = true;

		if (!modal.ready)
			return;

		if ($.isFunction(currentSettings.handleError))
			currentSettings.handleError(modal, currentSettings);

		modal.loading
			.addClass(currentSettings.errorClass)
			.html(currentSettings.contentError);
		$(currentSettings.closeSelector, modal.loading).click(removeModal);
		setMarginloading();
		modal.loading
			.css({
				marginTop: currentSettings.marginTopLoading+'px',
				marginLeft: currentSettings.marginLeftLoading+'px'
			});
	}

	// Put the content from modal.tmp to modal.content
	function fillContent() {
		debug('fillContent');
		if (!modal.tmp.html())
			return;

		modal.content.html(modal.tmp.contents());
		modal.tmp.empty();
		wrapContent();

		if ($.isFunction(currentSettings.endFillContent))
			currentSettings.endFillContent(modal, currentSettings);

		modal.content.append(modal.scripts);

		var currentSettingsNew = $.extend({}, currentSettings);
		if (resized.width)
			currentSettingsNew.width = null;
		if (resized.height)
			currentSettingsNew.height = null;
		$(currentSettings.closeSelector, modal.contentWrapper).click(removeModal);
		$(currentSettings.openSelector, modal.contentWrapper).nyroModal(currentSettingsNew);
	}

	// Wrap the content and update the modal size if needed
	function wrapContent() {
		debug('wrapContent');

		var wrap = $(currentSettings.wrap[currentSettings.type]);
		modal.content.append(wrap.children().remove());
		modal.contentWrapper.wrapInner(wrap);

		if (currentSettings.type == 'gallery') {
			// Set the action for the next and prev button (or remove them)

			var linkPrev = getGalleryLink(-1);
			if (linkPrev) {
				$('.nyroModalPrev', modal.contentWrapper)
					.attr('href', linkPrev.attr('href'))
					.click(function(e) {
						e.preventDefault();
						linkPrev.nyroModalManual(currentSettings);
						return false;
					});
			} else {
				$('.nyroModalPrev', modal.contentWrapper).remove();
			}
			var linkNext = getGalleryLink(1);
			if (linkNext) {
				$('.nyroModalNext', modal.contentWrapper)
					.attr('href', linkNext.attr('href'))
					.click(function(e) {
						e.preventDefault();
						linkNext.nyroModalManual(currentSettings);
						return false;
					});
			} else {
				$('.nyroModalNext', modal.contentWrapper).remove();
			}
		}

		calculateSize();
	}

	function getGalleryLink(dir) {
		if (currentSettings.type == 'gallery') {
			if (!currentSettings.ltr)
				dir *= -1;
			// next
			var gallery = $('[rel="'+currentSettings.from.rel+'"]');
			var currentIndex = gallery.index(currentSettings.from);
			var index = currentIndex + dir;
			if (index >= 0 && index < gallery.length)
				return gallery.eq(index);
		}
		return false;
	}

	// Calculate the size for the contentWrapper
	function calculateSize(resizing) {
		debug('calculateSize');

		if (!modal.wrapper)
			modal.wrapper = modal.contentWrapper.children(':first');

		resized.width = false;
		resized.height = false;
		if (currentSettings.autoSizable && (!currentSettings.width || !currentSettings.height)) {
			modal.contentWrapper.css({opacity: 0}).show();
			var tmp = {
				width: 'auto',
				height: 'auto'
			};
			if (currentSettings.width)
				tmp.width = currentSettings.width;
			if (currentSettings.height)
				tmp.height = currentSettings.height;
			modal.content.css(tmp);
			if (!currentSettings.width) {
				currentSettings.width = modal.content.width();
				resized.width = true;
			}
			if (!currentSettings.height) {
				currentSettings.height = modal.content.height();
				resized.height = true;
			}
			modal.contentWrapper.hide().css({opacity: 1});
		}

		currentSettings.width = Math.max(currentSettings.width, currentSettings.minWidth);
		currentSettings.height = Math.max(currentSettings.height, currentSettings.minHeight);

		var outerWrapper = getOuter(modal.contentWrapper);
		var outerWrapper2 = getOuter(modal.wrapper);
		var outerContent = getOuter(modal.content);

		var tmp = {
			content: {
				width: currentSettings.width,
				height: currentSettings.height
			},
			wrapper2: {
				width: currentSettings.width + outerContent.w.total,
				height: currentSettings.height + outerContent.h.total
			},
			wrapper: {
				width: currentSettings.width + outerContent.w.total + outerWrapper2.w.total,
				height: currentSettings.height + outerContent.h.total + outerWrapper2.h.total
			}
		};

		if (currentSettings.resizable) {
			var maxHeight = $(window).height()
					- currentSettings.padding*2
					- outerWrapper.h.border
					- (tmp.wrapper.height - currentSettings.height);
			var maxWidth = $(window).width()
					- currentSettings.padding*2
					- outerWrapper.w.border
					- (tmp.wrapper.width - currentSettings.width);

			if (tmp.content.height > maxHeight || tmp.content.width > maxWidth) {
				// We're gonna resize the modal as it will goes outside the view port
				if (currentSettings.type == 'image' || currentSettings.type == 'gallery') {
					// An image is resized proportionnaly
					var diffW = tmp.content.width - currentSettings.imgWidth;
					var diffH = tmp.content.height - currentSettings.imgHeight;
						if (diffH < 0) diffH = 0;
						if (diffW < 0) diffW = 0;
					var calcH = maxHeight - diffH;
					var calcW = maxWidth - diffW;
					var ratio = Math.min(calcH/currentSettings.imgHeight, calcW/currentSettings.imgWidth);

					calcH = Math.floor(currentSettings.imgHeight*ratio);
					calcW = Math.floor(currentSettings.imgWidth*ratio);
					$('img#nyroModalImg', modal.content).css({
						height: calcH+'px',
						width: calcW+'px'
					});
					tmp.content.height = calcH + diffH;
					tmp.content.width = calcW + diffW;
				} else {
					// For an HTML content, we simply decrease the size
					tmp.content.height = Math.min(tmp.content.height, maxHeight);
					tmp.content.width = Math.min(tmp.content.width, maxWidth);
				}
				tmp.wrapper2 = {
						width: tmp.content.width + outerContent.w.total,
						height: tmp.content.height + outerContent.h.total
					};
				tmp.wrapper = {
						width: tmp.content.width + outerContent.w.total + outerWrapper2.w.total,
						height: tmp.content.height + outerContent.h.total + outerWrapper2.h.total
					};
			}
		}

		modal.content.css($.extend({}, tmp.content, currentSettings.css.content));
		modal.wrapper.css($.extend({}, tmp.wrapper2, currentSettings.css.wrapper2));

		if (!resizing) {
			modal.contentWrapper.css($.extend({}, tmp.wrapper, currentSettings.css.wrapper));
			if (currentSettings.type == 'image' || currentSettings.type == 'gallery') {
				// Adding the title for the image
				var title = $('img', modal.content).attr('alt');
				$('img', modal.content).removeAttr('alt');
				if (title != currentSettings.defaultImgAlt) {
					var divTitle = $('<div>'+title+'</div>');
					modal.content.append(divTitle);
					if (currentSettings.setWidthImgTitle) {
						var outerDivTitle = getOuter(divTitle);
						divTitle.css({width: (tmp.content.width + outerContent.w.padding - outerDivTitle.w.total)+'px'});
					}
				}
			}

			if (!currentSettings.modal)
				modal.contentWrapper.prepend(currentSettings.closeButton);
		}

		if (currentSettings.title)
			modal.contentWrapper.prepend('<h1 id="nyroModalTitle">'+currentSettings.title+'</h1>');

		tmp.wrapper.borderW = outerWrapper.w.border;
		tmp.wrapper.borderH = outerWrapper.h.border;

		setCurrentSettings(tmp.wrapper);
		setMargin();
	}

	function removeModal(e) {
		debug('removeModal');
		if (e)
			e.preventDefault();
		if (modal.full && modal.ready) {
			modal.ready = false;
			modal.anim = true;
			modal.closing = true;
			if (modal.loadingShown || modal.transition) {
				currentSettings.hideLoading(modal, currentSettings, function() {
						modal.loading.hide();
						modal.loadingShown = false;
						modal.transition = false;
						currentSettings.hideBackground(modal, currentSettings, endRemove);
					});
			} else {
				if (fixFF)
					modal.content.css({position: ''}); // Fix Issue #10, remove the attribute
				modal.wrapper.css({overflow: 'hidden'}); // Used to fix a visual issue when hiding
				modal.content.css({overflow: 'hidden'}); // Used to fix a visual issue when hiding
				if ($.isFunction(currentSettings.beforeHideContent)) {
					currentSettings.beforeHideContent(modal, currentSettings, function() {
						currentSettings.hideContent(modal, currentSettings, function() {
							endHideContent();
							currentSettings.hideBackground(modal, currentSettings, endRemove);
						});
					});
				} else {
					currentSettings.hideContent(modal, currentSettings, function() {
							endHideContent();
							currentSettings.hideBackground(modal, currentSettings, endRemove);
						});
				}
			}
		}
		if (e)
			return false;
	}

	function showContentOrLoading() {
		debug('showContentOrLoading');
		if (modal.ready && !modal.anim) {
			if (modal.dataReady) {
				if (modal.tmp.html()) {
					modal.anim = true;
					if (modal.transition) {
						fillContent();
						currentSettings.hideTransition(modal, currentSettings, function() {
							modal.loading.hide();
							modal.transition = false;
							modal.loadingShown = false;
							endShowContent();
						});
					} else {
						currentSettings.hideLoading(modal, currentSettings, function() {
								modal.loading.hide();
								modal.loadingShown = false;
								fillContent();
								setMarginloading();
								currentSettings.showContent(modal, $.extend({}, currentSettings), endShowContent);
							});
					}
				}
			} else if (!modal.loadingShown && !modal.transition) {
				modal.anim = true;
				modal.loadingShown = true;
				if (modal.error)
					loadingError();
				else
					modal.loading.html(currentSettings.contentLoading);
				$(currentSettings.closeSelector, modal.loading).click(removeModal);
				setMarginloading();
				currentSettings.showLoading(modal, currentSettings, function(){modal.anim=false;showContentOrLoading();});
			}
		}
	}


	// -------------------------------------------------------
	// Private Data Loaded callback
	// -------------------------------------------------------

	function ajaxLoaded(data) {
		debug('AjaxLoaded: '+this.url);
		modal.tmp.html(currentSettings.selector
			?filterScripts($('<div>'+data+'</div>').find(currentSettings.selector).contents())
			:filterScripts(data));
		if (modal.tmp.html()) {
			modal.dataReady = true;
			showContentOrLoading();
		} else
			loadingError();
	}

	function formDataLoaded() {
		debug('formDataLoaded');
		var jFrom = $(currentSettings.from);
		jFrom.attr('action', jFrom.attr('action')+currentSettings.selector);
		jFrom.attr('target', '');
		$('input[name='+currentSettings.formIndicator+']', currentSettings.from).remove();
		var iframe = modal.tmp.children('iframe');
		var iframeContent = iframe.unbind('load').contents().find(currentSettings.selector || 'body').not('script[src]');
		iframe.attr('src', 'about:blank'); // Used to stop the loading in FF
		modal.tmp.html(iframeContent.html());
		if (modal.tmp.html()) {
			modal.dataReady = true;
			showContentOrLoading();
		} else
			loadingError();
	}


	// -------------------------------------------------------
	// Private Animation callback
	// -------------------------------------------------------

	function endHideContent() {
		debug('endHideContent');
		modal.anim = false;
		if (contentEltLast) {
			contentEltLast.append(modal.content.contents());
			contentEltLast= null;
		} else if (contentElt) {
			contentElt.append(modal.content.contents());
			contentElt= null;
		}
		modal.content.empty();
		modal.contentWrapper
			.empty()
			.removeAttr('style');

		if (modal.closing || modal.transition)
			modal.contentWrapper.hide();

		modal.contentWrapper
			.css(currentSettings.css.wrapper)
			.append(modal.content);
		showContentOrLoading();
	}

	function endRemove() {
		debug('endRemove');
		$(document).unbind('keydown', keyHandler);
		modal.anim = false;
		modal.full.remove();
		modal.full = null;
		if (isIE6) {
			body.css({height: '', width: '', position: '', overflow: ''});
			$('html').css({overflow: ''});
		}
		if ($.isFunction(currentSettings.endRemove))
			currentSettings.endRemove(modal, currentSettings);
	}

	function endBackground() {
		debug('endBackground');
		modal.ready = true;
		modal.anim = false;
		showContentOrLoading();
	}

	function endShowContent() {
		debug('endShowContent');
		modal.anim = false;
		modal.contentWrapper.css({opacity: ''}); // for the close button in IE
		fixFF = $.browser.mozilla && parseFloat($.browser.version) < 1.9 && currentSettings.type != 'gallery' && currentSettings.type != 'image';
		if (fixFF)
			modal.content.css({position: 'fixed'}); // Fix Issue #10
		if ($.isFunction(currentSettings.endShowContent))
			currentSettings.endShowContent(modal, currentSettings);
		if (resized.width)
			setCurrentSettings({width: null});
		if (resized.height)
			setCurrentSettings({height: null});
	}


	// -------------------------------------------------------
	// Utilities
	// -------------------------------------------------------

	// Get the selector from an url (as string)
	function getHash(url) {
		if (typeof url == 'string') {
			var hashPos = url.indexOf('#');
			if (hashPos > -1)
				return url.substring(hashPos);
		}
		return '';
	}

	// Filter an html content to remove the script[src]
	function filterScripts(data) {
		// Removing the body, head and html tag
		if (typeof data == 'string')
			data = data.replace(/<\/?(html|head|body)([^>]*)>/gi, '');
		var tmp = new Array();
		$.each($.clean({0:data}, this.ownerDocument), function() {
			if ($.nodeName(this, "script")) {
				if (!this.src || $(this).attr('rel') == 'forceLoad')
					modal.scripts.push(this);
			} else
				tmp.push(this);
		});
		return tmp;
	}

	// Get the vertical and horizontal margin, padding and border dimension
	function getOuter(elm) {
		elm = elm.get(0);
		var ret = {
			h: {
				margin: getCurCSS(elm, 'marginTop') + getCurCSS(elm, 'marginBottom'),
				border: getCurCSS(elm, 'borderTopWidth') + getCurCSS(elm, 'borderBottomWidth'),
				padding: getCurCSS(elm, 'paddingTop') + getCurCSS(elm, 'paddingBottom')
			},
			w: {
				margin: getCurCSS(elm, 'marginLeft') + getCurCSS(elm, 'marginRight'),
				border: getCurCSS(elm, 'borderLeftWidth') + getCurCSS(elm, 'borderRightWidth'),
				padding: getCurCSS(elm, 'paddingLeft') + getCurCSS(elm, 'paddingRight')
			}
		};

		ret.h.outer = ret.h.margin + ret.h.border;
		ret.w.outer = ret.w.margin + ret.w.border;

		ret.h.inner = ret.h.padding + ret.h.border;
		ret.w.inner = ret.w.padding + ret.w.border;

		ret.h.total = ret.h.outer + ret.h.padding;
		ret.w.total = ret.w.outer + ret.w.padding;

		return ret;
	}

	function getCurCSS(elm, name) {
		var ret = parseInt($.curCSS(elm, name, true));
		if (isNaN(ret))
			ret = 0;
		return ret;
	}

	function isDoctypeStrict() {
		var doctype = '';
		if ($.browser.opera) {
			return true;
		} else if ($.browser.msie) {
			var re = /\s+(X?HTML)\s+([\d\.]+)\s*([^\/]+)*\//gi;
			var res = false;
			if($.browser.msie)
				res = document.all[0].nodeType == 8 ? re.test(document.all[0].nodeValue) : false;
			if (res)
				doctype = RegExp.$3;
		} else
			doctype = document.doctype.systemId;
		return doctype.toLowerCase().indexOf('strict') > -1
	}

	// Proxy Debug function
	function debug(msg) {
		if ($.fn.nyroModal.settings.debug || currentSettings && currentSettings.debug)
			nyroModalDebug(msg, modal, currentSettings || {});
	}

	// -------------------------------------------------------
	// Default animation function
	// -------------------------------------------------------

	function showBackground(elts, settings, callback) {
		elts.bg.css({opacity:0}).fadeTo(500, 0.75, callback);
	}

	function hideBackground(elts, settings, callback) {
		elts.bg.fadeOut(300, callback);
	}

	function showLoading(elts, settings, callback) {
		elts.loading
			.css({
				marginTop: settings.marginTopLoading+'px',
				marginLeft: settings.marginLeftLoading+'px',
				opacity: 0
			})
			.show()
			.animate({
				opacity: 1
			}, {complete: callback, duration: 400});
	}

	function hideLoading(elts, settings, callback) {
		callback();
	}

	function showContent(elts, settings, callback) {
		elts.loading
			.css({
				marginTop: settings.marginTopLoading+'px',
				marginLeft: settings.marginLeftLoading+'px'
			})
			.show()
			.animate({
				width: settings.width+'px',
				height: settings.height+'px',
				marginTop: settings.marginTop+'px',
				marginLeft: settings.marginLeft+'px'
			}, {duration: 350, complete: function() {
				elts.contentWrapper
					.css({
						width: settings.width+'px',
						height: settings.height+'px',
						marginTop: settings.marginTop+'px',
						marginLeft: settings.marginLeft+'px'
					})
					.show();
					elts.loading.fadeOut(200, callback);
				}
			});
	}

	function hideContent(elts, settings, callback) {
		elts.contentWrapper
			.animate({
				height: '50px',
				width: '50px',
				marginTop: (-(25+settings.borderH)/2 + settings.marginScrollTop)+'px',
				marginLeft: (-(25+settings.borderW)/2 + settings.marginScrollLeft)+'px'
			}, {duration: 350, complete: function() {
				elts.contentWrapper.hide();
				callback();
			}});
	}

	function showTransition(elts, settings, callback) {
		// Put the loading with the same dimensions of the current content
		elts.loading
			.css({
				marginTop: elts.contentWrapper.css('marginTop'),
				marginLeft: elts.contentWrapper.css('marginLeft'),
				height: elts.contentWrapper.css('height'),
				width: elts.contentWrapper.css('width'),
				opacity: 0
			})
			.show()
			.fadeTo(400, 1, function() {
					elts.contentWrapper.hide();
					callback();
				});
	}

	function hideTransition(elts, settings, callback) {
		// Place the content wrapper underneath the the loading with the right dimensions
		elts.contentWrapper
			.hide()
			.css({
				width: settings.width+'px',
				marginLeft: settings.marginLeft+'px',
				height: settings.height+'px',
				marginTop: settings.marginTop+'px',
				opacity: 1
			});
		elts.loading
			.animate({
				width: settings.width+'px',
				marginLeft: settings.marginLeft+'px',
				height: settings.height+'px',
				marginTop: settings.marginTop+'px'
			}, {complete: function() {
					elts.contentWrapper.show();
					elts.loading.fadeOut(400, function() {
						elts.loading.hide();
						callback();
					});
				}, duration: 350});
	}

	function resize(elts, settings, callback) {
		elts.contentWrapper
			.animate({
				width: settings.width+'px',
				marginLeft: settings.marginLeft+'px',
				height: settings.height+'px',
				marginTop: settings.marginTop+'px'
			}, {complete: callback, duration: 400});
	}

	function updateBgColor(elts, settings, callback) {
		if (!$.fx.step.backgroundColor) {
			elts.bg.css({backgroundColor: settings.bgColor});
			callback();
		} else
			elts.bg
				.animate({
					backgroundColor: settings.bgColor
				}, {complete: callback, duration: 400});
	}

	// -------------------------------------------------------
	// Default initialization
	// -------------------------------------------------------

	$($.fn.nyroModal.settings.openSelector).nyroModal();

});

// Default debug function, to be overwritten if needed
//      Be aware that the settings parameter could be empty
function nyroModalDebug(msg, elts, settings) {
	console.log(msg);
	if (elts.full)
		elts.bg.prepend(msg+'<br />');
}

