/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
﻿/*!
 * jQuery blockUI plugin
 * Version 2.39 (23-MAY-2011)
 * @requires jQuery v1.2.3 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2010 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function($) {

if (/1\.(0|1|2)\.(0|1|2)/.test($.fn.jquery) || /^1.1/.test($.fn.jquery)) {
	alert('blockUI requires jQuery v1.2.3 or later!  You are using v' + $.fn.jquery);
	return;
}

$.fn._fadeIn = $.fn.fadeIn;

var noOp = function() {};

// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
// retarded userAgent strings on Vista)
var mode = document.documentMode || 0;
var setExpr = $.browser.msie && (($.browser.version < 8 && !mode) || mode < 8);
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;

// global $ methods for blocking/unblocking the entire page
$.blockUI   = function(opts) { install(window, opts); };
$.unblockUI = function(opts) { remove(window, opts); };

// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
$.growlUI = function(title, message, timeout, onClose) {
	var $m = $('<div class="growlUI"></div>');
	if (title) $m.append('<h1>'+title+'</h1>');
	if (message) $m.append('<h2>'+message+'</h2>');
	if (timeout == undefined) timeout = 3000;
	$.blockUI({
		message: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout: timeout, showOverlay: false,
		onUnblock: onClose, 
		css: $.blockUI.defaults.growlCSS
	});
};

// plugin method for blocking element content
$.fn.block = function(opts) {
	return this.unblock({ fadeOut: 0 }).each(function() {
		if ($.css(this,'position') == 'static')
			this.style.position = 'relative';
		if ($.browser.msie)
			this.style.zoom = 1; // force 'hasLayout'
		install(this, opts);
	});
};

// plugin method for unblocking element content
$.fn.unblock = function(opts) {
	return this.each(function() {
		remove(this, opts);
	});
};

$.blockUI.version = 2.39; // 2nd generation blocking at no extra cost!

// override these in your code to change the default behavior and style
$.blockUI.defaults = {
	// message displayed when blocking (use null for no message)
	message:  '<h1>Please wait...</h1>',

	title: null,	  // title string; only used when theme == true
	draggable: true,  // only used when theme == true (requires jquery-ui.js to be loaded)
	
	theme: false, // set to true to use with jQuery UI themes
	
	// styles for the message when blocking; if you wish to disable
	// these and use an external stylesheet then do this in your code:
	// $.blockUI.defaults.css = {};
	css: {
		padding:	0,
		margin:		0,
		width:		'30%',
		top:		'40%',
		left:		'35%',
		textAlign:	'center',
		color:		'#000',
		border:		'3px solid #aaa',
		backgroundColor:'#fff',
		cursor:		'wait'
	},
	
	// minimal style set used when themes are used
	themedCSS: {
		width:	'30%',
		top:	'40%',
		left:	'35%'
	},

	// styles for the overlay
	overlayCSS:  {
		backgroundColor: '#000',
		opacity:	  	 0.6,
		cursor:		  	 'wait'
	},

	// styles applied when using $.growlUI
	growlCSS: {
		width:  	'350px',
		top:		'10px',
		left:   	'',
		right:  	'10px',
		border: 	'none',
		padding:	'5px',
		opacity:	0.6,
		cursor: 	'default',
		color:		'#fff',
		backgroundColor: '#000',
		'-webkit-border-radius': '10px',
		'-moz-border-radius':	 '10px',
		'border-radius': 		 '10px'
	},
	
	// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
	// (hat tip to Jorge H. N. de Vasconcelos)
	iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

	// force usage of iframe in non-IE browsers (handy for blocking applets)
	forceIframe: false,

	// z-index for the blocking overlay
	baseZ: 1000,

	// set these to true to have the message automatically centered
	centerX: true, // <-- only effects element blocking (page block controlled via css above)
	centerY: true,

	// allow body element to be stetched in ie6; this makes blocking look better
	// on "short" pages.  disable if you wish to prevent changes to the body height
	allowBodyStretch: true,

	// enable if you want key and mouse events to be disabled for content that is blocked
	bindEvents: true,

	// be default blockUI will supress tab navigation from leaving blocking content
	// (if bindEvents is true)
	constrainTabKey: true,

	// fadeIn time in millis; set to 0 to disable fadeIn on block
	fadeIn:  200,

	// fadeOut time in millis; set to 0 to disable fadeOut on unblock
	fadeOut:  400,

	// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
	timeout: 0,

	// disable if you don't want to show the overlay
	showOverlay: true,

	// if true, focus will be placed in the first available input field when
	// page blocking
	focusInput: true,

	// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
	applyPlatformOpacityRules: true,
	
	// callback method invoked when fadeIn has completed and blocking message is visible
	onBlock: null,

	// callback method invoked when unblocking has completed; the callback is
	// passed the element that has been unblocked (which is the window object for page
	// blocks) and the options that were passed to the unblock call:
	//	 onUnblock(element, options)
	onUnblock: null,

	// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
	quirksmodeOffsetHack: 4,

	// class name of the message block
	blockMsgClass: 'blockMsg'
};

// private data and functions follow...

var pageBlock = null;
var pageBlockEls = [];

function install(el, opts) {
	var full = (el == window);
	var msg = opts && opts.message !== undefined ? opts.message : undefined;
	opts = $.extend({}, $.blockUI.defaults, opts || {});
	opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
	var css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
	var themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
	msg = msg === undefined ? opts.message : msg;

	// remove the current block (if there is one)
	if (full && pageBlock)
		remove(window, {fadeOut:0});

	// if an existing element is being used as the blocking content then we capture
	// its current place in the DOM (and current display style) so we can restore
	// it when we unblock
	if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
		var node = msg.jquery ? msg[0] : msg;
		var data = {};
		$(el).data('blockUI.history', data);
		data.el = node;
		data.parent = node.parentNode;
		data.display = node.style.display;
		data.position = node.style.position;
		if (data.parent)
			data.parent.removeChild(node);
	}

	$(el).data('blockUI.onUnblock', opts.onUnblock);
	var z = opts.baseZ;

	// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
	// layer1 is the iframe layer which is used to supress bleed through of underlying content
	// layer2 is the overlay layer which has opacity and a wait cursor (by default)
	// layer3 is the message content that is displayed while blocking

	var lyr1 = ($.browser.msie || opts.forceIframe) 
		? $('<iframe class="blockUI" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+opts.iframeSrc+'"></iframe>')
		: $('<div class="blockUI" style="display:none"></div>');
	
	var lyr2 = opts.theme 
	 	? $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:'+ (z++) +';display:none"></div>')
	 	: $('<div class="blockUI blockOverlay" style="z-index:'+ (z++) +';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>');

	var lyr3, s;
	if (opts.theme && full) {
		s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:fixed">' +
				'<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
				'<div class="ui-widget-content ui-dialog-content"></div>' +
			'</div>';
	}
	else if (opts.theme) {
		s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:'+(z+10)+';display:none;position:absolute">' +
				'<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">'+(opts.title || '&nbsp;')+'</div>' +
				'<div class="ui-widget-content ui-dialog-content"></div>' +
			'</div>';
	}
	else if (full) {
		s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:'+(z+10)+';display:none;position:fixed"></div>';
	}			 
	else {
		s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:'+(z+10)+';display:none;position:absolute"></div>';
	}
	lyr3 = $(s);

	// if we have a message, style it
	if (msg) {
		if (opts.theme) {
			lyr3.css(themedCSS);
			lyr3.addClass('ui-widget-content');
		}
		else 
			lyr3.css(css);
	}

	// style the overlay
	if (!opts.theme && (!opts.applyPlatformOpacityRules || !($.browser.mozilla && /Linux/.test(navigator.platform))))
		lyr2.css(opts.overlayCSS);
	lyr2.css('position', full ? 'fixed' : 'absolute');

	// make iframe layer transparent in IE
	if ($.browser.msie || opts.forceIframe)
		lyr1.css('opacity',0.0);

	//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
	var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
	$.each(layers, function() {
		this.appendTo($par);
	});
	
	if (opts.theme && opts.draggable && $.fn.draggable) {
		lyr3.draggable({
			handle: '.ui-dialog-titlebar',
			cancel: 'li'
		});
	}

	// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
	var expr = setExpr && (!$.boxModel || $('object,embed', full ? null : el).length > 0);
	if (ie6 || expr) {
		// give body 100% height
		if (full && opts.allowBodyStretch && $.boxModel)
			$('html,body').css('height','100%');

		// fix ie6 issue when blocked element has a border width
		if ((ie6 || !$.boxModel) && !full) {
			var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
			var fixT = t ? '(0 - '+t+')' : 0;
			var fixL = l ? '(0 - '+l+')' : 0;
		}

		// simulate fixed position
		$.each([lyr1,lyr2,lyr3], function(i,o) {
			var s = o[0].style;
			s.position = 'absolute';
			if (i < 2) {
				full ? s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"')
					 : s.setExpression('height','this.parentNode.offsetHeight + "px"');
				full ? s.setExpression('width','jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"')
					 : s.setExpression('width','this.parentNode.offsetWidth + "px"');
				if (fixL) s.setExpression('left', fixL);
				if (fixT) s.setExpression('top', fixT);
			}
			else if (opts.centerY) {
				if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
				s.marginTop = 0;
			}
			else if (!opts.centerY && full) {
				var top = (opts.css && opts.css.top) ? parseInt(opts.css.top) : 0;
				var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
				s.setExpression('top',expression);
			}
		});
	}

	// show the message
	if (msg) {
		if (opts.theme)
			lyr3.find('.ui-widget-content').append(msg);
		else
			lyr3.append(msg);
		if (msg.jquery || msg.nodeType)
			$(msg).show();
	}

	if (($.browser.msie || opts.forceIframe) && opts.showOverlay)
		lyr1.show(); // opacity is zero
	if (opts.fadeIn) {
		var cb = opts.onBlock ? opts.onBlock : noOp;
		var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
		var cb2 = msg ? cb : noOp;
		if (opts.showOverlay)
			lyr2._fadeIn(opts.fadeIn, cb1);
		if (msg)
			lyr3._fadeIn(opts.fadeIn, cb2);
	}
	else {
		if (opts.showOverlay)
			lyr2.show();
		if (msg)
			lyr3.show();
		if (opts.onBlock)
			opts.onBlock();
	}

	// bind key and mouse events
	bind(1, el, opts);

	if (full) {
		pageBlock = lyr3[0];
		pageBlockEls = $(':input:enabled:visible',pageBlock);
		if (opts.focusInput)
			setTimeout(focus, 20);
	}
	else
		center(lyr3[0], opts.centerX, opts.centerY);

	if (opts.timeout) {
		// auto-unblock
		var to = setTimeout(function() {
			full ? $.unblockUI(opts) : $(el).unblock(opts);
		}, opts.timeout);
		$(el).data('blockUI.timeout', to);
	}
};

// remove the block
function remove(el, opts) {
	var full = (el == window);
	var $el = $(el);
	var data = $el.data('blockUI.history');
	var to = $el.data('blockUI.timeout');
	if (to) {
		clearTimeout(to);
		$el.removeData('blockUI.timeout');
	}
	opts = $.extend({}, $.blockUI.defaults, opts || {});
	bind(0, el, opts); // unbind events

	if (opts.onUnblock === null) {
		opts.onUnblock = $el.data('blockUI.onUnblock');
		$el.removeData('blockUI.onUnblock');
	}

	var els;
	if (full) // crazy selector to handle odd field errors in ie6/7
		els = $('body').children().filter('.blockUI').add('body > .blockUI');
	else
		els = $('.blockUI', el);

	if (full)
		pageBlock = pageBlockEls = null;

	if (opts.fadeOut) {
		els.fadeOut(opts.fadeOut);
		setTimeout(function() { reset(els,data,opts,el); }, opts.fadeOut);
	}
	else
		reset(els, data, opts, el);
};

// move blocking element back into the DOM where it started
function reset(els,data,opts,el) {
	els.each(function(i,o) {
		// remove via DOM calls so we don't lose event handlers
		if (this.parentNode)
			this.parentNode.removeChild(this);
	});

	if (data && data.el) {
		data.el.style.display = data.display;
		data.el.style.position = data.position;
		if (data.parent)
			data.parent.appendChild(data.el);
		$(el).removeData('blockUI.history');
	}

	if (typeof opts.onUnblock == 'function')
		opts.onUnblock(el,opts);
};

// bind/unbind the handler
function bind(b, el, opts) {
	var full = el == window, $el = $(el);

	// don't bother unbinding if there is nothing to unbind
	if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
		return;
	if (!full)
		$el.data('blockUI.isBlocked', b);

	// don't bind events when overlay is not in use or if bindEvents is false
	if (!opts.bindEvents || (b && !opts.showOverlay)) 
		return;

	// bind anchors and inputs for mouse and key events
	var events = 'mousedown mouseup keydown keypress';
	b ? $(document).bind(events, opts, handler) : $(document).unbind(events, handler);

// former impl...
//	   var $e = $('a,:input');
//	   b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
};

// event handler to suppress keyboard/mouse events when blocking
function handler(e) {
	// allow tab navigation (conditionally)
	if (e.keyCode && e.keyCode == 9) {
		if (pageBlock && e.data.constrainTabKey) {
			var els = pageBlockEls;
			var fwd = !e.shiftKey && e.target === els[els.length-1];
			var back = e.shiftKey && e.target === els[0];
			if (fwd || back) {
				setTimeout(function(){focus(back)},10);
				return false;
			}
		}
	}
	var opts = e.data;
	// allow events within the message content
	if ($(e.target).parents('div.' + opts.blockMsgClass).length > 0)
		return true;

	// allow events for content that is not being blocked
	return $(e.target).parents().children().filter('div.blockUI').length == 0;
};

function focus(back) {
	if (!pageBlockEls)
		return;
	var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
	if (e)
		e.focus();
};

function center(el, x, y) {
	var p = el.parentNode, s = el.style;
	var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
	var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
	if (x) s.left = l > 0 ? (l+'px') : '0';
	if (y) s.top  = t > 0 ? (t+'px') : '0';
};

function sz(el, p) {
	return parseInt($.css(el,p))||0;
};

})(jQuery);

(function($) {
	var settings;	

	$.fn.tireSearch = function(options) {
		var newOptions = $.extend({}, {element: $(this)}, options);
		$.tireSearchBox.search(newOptions);
		return this;
	};
	
	$.tireSearchBox = {
		_init: function(options) {
			settings = $.extend({
				cachingEnabled: false,
				defaultEmptyValue: "-1",
				apiUrl: "#",
				tirePageUrl: "#",
				fields: [],
				labels: [],
                tabs: [],
				columns: 1,
                currentTab: 1,
                numberOfTabs: 2,
				parameters: {},
				namespace: "tireSearch",
				loaderImage: "images/loader.gif",
				requiredTxt: "verplicht",
				errorMsg: null,
				resetBtn: "Reset",
				sendBtn: "Find my tire"
			}, options || {});

            if (settings.currentTab < 1) settings.currentTab = 1;
            if (settings.columns < 1) settings.columns = 1;
            if (settings.numberOfTabs < 1) settings.numberOfTabs = 1;

			$.tireSearchBox._generateComponents();
		},
		
		_generateUniqueUrl: function(url) {
			var result = url;
			if (!settings.cachingEnabled) {
				if (result.indexOf('?') > 0) {
					result += '&';
				} else {
					result += '?';
				}
				result += (new Date().getTime());
			}
			return result;
		},

        _generateSearchTabs: function() {
            if (settings.tabs && settings.numberOfTabs > 1) {
                var generatedTabs = [], counter = 0;
                generatedTabs[counter] = "<li>" + $.tireSearchBox._getLabelByIndex("searchon") + "</li>";
                counter++;

                for (var j = 0; j < settings.tabs.length; j++) {
                    if (settings.tabs[j]) {
                        var styleClass = (settings.namespace+"-tab");
                        if (settings.currentTab == (j + 1)) {
                            styleClass = (settings.namespace+"-tab-selected");
                        }
                        generatedTabs[counter] = '<li id="' + (settings.namespace+'-'+settings.tabs[j].id) + '" class="' + styleClass + '"><a href="#" title="' + settings.tabs[j].label + '" rel="nofollow">' + settings.tabs[j].label + '</a></li>';
                        counter++;
                    }
                }

                settings.element.append($("<ul>").addClass((settings.namespace+"-tabs")).html(generatedTabs.join("")));
                $(("ul." + (settings.namespace+"-tabs") + " li a")).click($.tireSearchBox._switchSearchFields);
            }
        },

        _generateSearchFields: function() {
            var fieldListElement = settings.element.find(("#" + settings.namespace + "-fields"));
            if (fieldListElement.length > 0) {
                fieldListElement.empty();

                // Selectboxes
                settings.fields.sort($.tireSearchBox._sortBySequence);
                var numberOfElements = settings.fields.length;
                if ((numberOfElements % settings.columns) != 0) {
                    numberOfElements = (parseInt((numberOfElements / settings.columns)) + 1) * settings.columns;
                }

                for (var i = 0; i < numberOfElements; i++) {
                    if ((i % settings.columns) == 0) {
                        fieldListElement.append($("<tr>"));
                    }

                    var lastRow = fieldListElement.find("tr:last-child")[0];
                    var field = $.tireSearchBox._findFieldBySequence((i + 1));
                    if (field) {
                        var fieldId = (settings.namespace + '-' + field.name);
                        var fieldLabel = field.label;
                        var fieldReqLabel = "";
                        var allLabel = field.allLabel;

                        if (field.required && field.required[(settings.currentTab - 1)]) {
                            fieldReqLabel += " <span class=\"required\">*</span>";
                        }

                        if (field.visible && field.visible[(settings.currentTab - 1)]) {
                            $(lastRow).append($("<td>").append($("<label>").attr({'for':fieldId}).text(fieldLabel)
                                .append(fieldReqLabel)));
                            $(lastRow).append($("<td>")
                                .append($("<" + "select" + ">").attr({name:field.name, id:fieldId})
                                    .change(function () {
                                        settings.parameters = $.tireSearchBox._getChosenValues();
                                        $.tireSearchBox._loadData(settings.parameters, true);
                                    })
                                    .append($("<" + "option" + ">").attr({selected:"selected"})
                                        .val(settings.defaultEmptyValue).text(allLabel))
                                )
                            );
                        } else if (settings.column > 1) {
                            $(lastRow).append("<td>&nbsp;</td><td>&nbsp;</td>");
                        }
                    } else {
                        $(lastRow).append("<td>&nbsp;</td><td>&nbsp;</td>");
                    }
                }

                // Required msg
                fieldListElement.append($("<tr>").attr({id:(settings.namespace + '-required')})
                    .addClass("tireSearchMsg")
                    .append($("<td>").append($("<span>").addClass("required").text("*")))
                    .append($("<td>").addClass("msg").text(settings.requiredTxt))
                );

                // Total found result
                fieldListElement.append($("<tr>").attr({id:(settings.namespace + '-totalResult')})
                    .addClass("tireSearchResult")
                    .append($("<td>").text($.tireSearchBox._getLabelByIndex("total")))
                    .append($("<td>").addClass("number"))
                );

                // Search buttons
                var searchBtnId = (settings.namespace + '-searchBtn');
                fieldListElement.append($("<tr>").addClass("searchButtons")
                    .append($("<td>")
                        .append($("<input>").attr({type:"button"})
                            .addClass("button").val(settings.resetBtn)
                            .click(function() {
                                $.tireSearchBox._resetSearchBox();
                            }))
                        )
                    .append($("<td>").addClass("submitBtn")
                        .append($("<input>").attr({id: searchBtnId, type:"submit", disabled: "disabled"})
                            .addClass("button searchBtn").val(settings.sendBtn))
                    )
                );
            }
        },

		_generateComponents: function() {
            // Generate tabs
            $.tireSearchBox._generateSearchTabs();

            // Generate fields
            var elements = [], counter = 0;
            elements[counter] = '<div class="selector" id="' + (settings.namespace+"-selector") + '">';
            counter++;
            elements[counter] = '<form action="' + settings.tirePageUrl + '" method="post" name="' + settings.namespace + '">';
            counter++;
            elements[counter] = '<input type="hidden" id="' + (settings.namespace+"-searchMode") + '" name="searchMode" value="' + settings.currentTab + '"/>';
            counter++;
            elements[counter] = '<table class="tireSearch" id="' + (settings.namespace+"-fields") + '">';
            counter++;
            elements[counter] = '</table></form></div>';
            counter++;
            settings.element.append(elements.join(""));

			$.tireSearchBox._generateSearchFields();
		},

        _findFieldBySequence: function(seqNumber) {
            var result = null;
            for (var i = 0; i < settings.fields.length; i++) {
                var field = settings.fields[i];
                if (field && (field.sequence[(settings.currentTab - 1)] == seqNumber)) {
                    result = field;
                    break;
                }
            }
            return result;
        },

        _sortBySequence: function(item1, item2) {
            var val1 = 0, val2 = 0;
            if (item1 && item1.sequence && item1.sequence[(settings.currentTab - 1)]) {
                val1 = item1.sequence[(settings.currentTab - 1)];
            }

            if (item2 && item2.sequence && item2.sequence[(settings.currentTab - 1)]) {
                val2 = item2.sequence[(settings.currentTab - 1)];
            }
            return val1 - val2;
        },

		_setLoadingStage: function(enable) {
			if (enable) {
				$(("#"+settings.namespace+"-selector")).block({
					message: '<img src="' + settings.loaderImage + '" alt="loading" />'
				});
			} else {
				$(("#"+settings.namespace+"-selector")).unblock();
			}
		},
		
		_enableSearchButton: function(total) {
			var conditionSatisfied = true;
			if (total != 1) {
				for (var i = 0; i < settings.fields.length; i++) {
					var field = settings.fields[i];
					var value = $(('#' + settings.namespace + '-' + field.name)).val();
					if (field.required[(settings.currentTab - 1)] && (value == settings.defaultEmptyValue)) {
						conditionSatisfied = conditionSatisfied && false;
					}
				}
			}
			
			if (conditionSatisfied) {
				$(("#" + settings.namespace + '-searchBtn')).removeAttr("disabled");
			} else {
				$(("#" + settings.namespace + '-searchBtn')).attr({disabled:"disabled"});
			}
		},
		
		_getChosenValues: function() {
			var result = {};
			for (var i = 0; i < settings.fields.length; i++) {
				var field = settings.fields[i];
                if (field && field.visible[(settings.currentTab - 1)]) {
                    var value = $(('#' + settings.namespace + '-' + field.name)).val();
                    if (value != settings.defaultEmptyValue) {
                        result[field.name] = value;
                    }
                }
			}
			return result;
		},
		
		_getLabel: function(field, value) {
			var label = value;
			if (field && field.type == 'label') {
				label = $.tireSearchBox._getLabelByIndex(value);
			}
			return label;
		},
		
		_getLabelByIndex: function(value) {
			var options = $.grep(settings.labels, function(e) {
				return e.index == (value + '');
			});
			return (options && options.length > 0) ? options[0].label : value;
		},
		
		_populateSearchBox: function(data) {
			var totalResult = 0;
			if (data["total"]) {
				var totalResultId = ('#' + settings.namespace + '-totalResult');
				$(totalResultId).children("td.number").text(data["total"]);
				$(totalResultId).show();
				totalResult = data["total"];
			}
		
			for (var i = 0; i < settings.fields.length; i++) {
				var field = settings.fields[i];
				var fieldId = ('#' + settings.namespace + '-' + field.name);
                var options = [], counter = 0, allLabel = field.allLabel;
				
				$(fieldId).empty();
                options[counter] = '<option value="' + settings.defaultEmptyValue + '">' + allLabel + "</option>";
                counter++;
				if (data[field.name] && (data[field.name].length > 0)) {
					var values = data[field.name];
					
					// Loop through all options
                    var label = '';
					if (data[field.name].length > 1) {
						for (var j = 0; j < values.length; j++) {
							var value = values[j];
							label = $.tireSearchBox._getLabel(field, value);
							if (settings.parameters[field.name] && 
								(settings.parameters[field.name] == value)) {
                                options[counter] = '<option value="' + value + '" selected="selected">' + label + "</option>";
							} else {
                                options[counter] = '<option value="' + value + '">' + label + "</option>";
							}
                            counter++;
						}
					} else {
						// Select this value if there is only one option left
						label = $.tireSearchBox._getLabel(field, values[0]);
                        options[counter] = '<option value="' + values[0] + '" selected="selected">' + label + "</option>";
                        counter++;
					}
				}
                $(fieldId).html(options.join(""));
			}
			
			$.tireSearchBox._setLoadingStage(false);
			$.tireSearchBox._enableSearchButton(totalResult);
		},
		
		_resetSearchBox: function() {
			settings.parameters = {};
			$.tireSearchBox._loadData(settings.parameters, false);
		},

        _switchSearchFields: function(event) {
            if (settings.numberOfTabs > 1) {
                event.stopPropagation();
                
                var chosenTab = $(event.target).parent().get(0).id;
                for (var i = 0; i < settings.tabs.length; i++) {
                    if (settings.tabs[i] && ((settings.namespace + '-' + settings.tabs[i].id) == chosenTab)) {
                        settings.currentTab = (i + 1);
                        $(("#" + settings.namespace+"-searchMode")).val(settings.currentTab);
                        $(("ul." + (settings.namespace+"-tabs") + " li." + (settings.namespace+"-tab-selected"))).removeClass().addClass((settings.namespace+"-tab"));
                        $(("#" + chosenTab)).addClass((settings.namespace+"-tab-selected"));
                        break;
                    }
                }

                $.tireSearchBox._generateSearchFields();
                $.tireSearchBox._loadData(settings.parameters, true);
            }
            return false;
		},
		
		_loadData: function(parameters, repopulate) {
			$.tireSearchBox._setLoadingStage(true);
			$.ajax({
				url: $.tireSearchBox._generateUniqueUrl(settings.apiUrl),
				dataType: 'jsonp',
				data: parameters,
				error: function(req, status, errorThrown) {
					$.tireSearchBox._setLoadingStage(false);
					var msg = errorThrown;
					if (settings.errorMsg) {
						msg = settings.errorMsg;
					} 
					alert(msg);
				},
				success: $.tireSearchBox._populateSearchBox
			});
		},
		
		search: function(options) {
			$.tireSearchBox._init(options);
			$.tireSearchBox._loadData(settings.parameters, false);
		}
	};
})(jQuery);
var settings = {debug: true,
                latitude: 52.2,
                longitude: 4.9,
                zoom: 6,
                serverUrl: '',
                site: '',
                country: 'nl',
                directionsContainer: null,
                cookieName: 'mapcoordinates',
                includeDealers: true,
                loadCookie: true,
                includeUserLocation: true,
                chosenDealer: undefined,
                selectedDealer: null,
                setupPage: setupPage,
                nearestDealerLink: '/dealers-in-de-buurt',
                defaultErrorText: 'Problems occurred, trying again later',
                userMarkerText: 'Your location',
                dealerMarkersUrl: 'http://maps.google.com/mapfiles/marker',
                dealersContainer: '#local-dealers',
                dealersPositions: new Array(),
                numberOfMarkers: 5,
                visibleDealers: 5,
                invalidZipCodeText: 'Zipcode not found!'};

var map;
var directions;

function initializeMap(mapContainer) {
  var fromCookie = false;
  map = new google.maps.Map2(document.getElementById(mapContainer));
  map.addControl(new GSmallMapControl());
  map.disableInfoWindow();
  //map.enableScrollWheelZoom();

  if (settings.directionsContainer) {
    directions = new GDirections(map, document.getElementById(settings.directionsContainer));
  }

  // Cookie available? Use that!
  if (settings.loadCookie) {
    var cookieValue = jQuery.cookie(settings.cookieName);
    if (cookieValue) {
    	try {
		      var cookieItems = cookieValue.split(':');
		      settings.latitude = parseFloat(cookieItems[0].split('=')[1]);
		      settings.longitude = parseFloat(cookieItems[1].split('=')[1]);
		      settings.zoom = parseInt(cookieItems[2].split('=')[1]);
		      settings.latitude = Math.round(settings.latitude*100)/100;
		      settings.longitude = Math.round(settings.longitude*100)/100;
    	} catch (e) {
			//ignore and load normally
    		if (console) {console.log(e);}
		}
      fromCookie = true;
    }
  }

  // Try to find location on map
  // Google client location available?
  if (!fromCookie && google.loader.ClientLocation) {
    settings.latitude = google.loader.ClientLocation.latitude;
    settings.longitude = google.loader.ClientLocation.longitude;
    settings.zoom = 9;
  }

  // Geolocation available and allowed by user?
  if (!fromCookie && navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      settings.latitude = position.coords.latitude;
      settings.longitude = position.coords.longitude;
      settings.zoom = 10;
      centerMap(settings.latitude, settings.longitude, settings.zoom, settings.includeDealers);
    });
  }
  centerMap(settings.latitude, settings.longitude, settings.zoom, settings.includeDealers);
  GEvent.addListener(map, "error", handleErrors);
}

function centerMap(latitude, longitude, zoom, includeDealers) {
  // Center the map on the given coordinates
  map.setCenter(new google.maps.LatLng(latitude, longitude));
  map.setZoom(zoom);

  // Find the nearest dealers
  if (includeDealers) {
    var url = (settings.serverUrl + 'dealers/search?site=' + settings.site);
    jQuery.ajax({
      url: url,
      data: {
        lat: latitude,
        lng: longitude,
        max: 5
      },
      dataType: 'jsonp',
      success: showLocalDealers
    });
  }

  // Store the given coordinates in a cookie
  storeMapCoordinates(latitude, longitude, zoom);
}

function getDealerPosition(id) {
  var result = null;
  if (id && settings.dealersPositions) {
    for (var i in settings.dealersPositions) {
      var dealer = settings.dealersPositions[i];
      if (id == dealer.id) {
        result = dealer.position;
      }
    }
  }
  return result;
}

function getPositions(includeUserLocation, useChosenDealer) {
  var result = new Array();
  if (includeUserLocation) {
    var position = new GLatLng(settings.latitude, settings.longitude);
    result.push(position);
  }

  for (var i in settings.dealersPositions) {
    var dealer = settings.dealersPositions[i];
    if (useChosenDealer) {
      if (!settings.chosenDealer || (settings.chosenDealer == dealer.id)) {
        result.push(dealer.position);
      }
    }
    else {
   		result.push(dealer.position);
    }
  }
  return result;
}

function showLocalDealers(dealers) {
  map.clearOverlays();

  if (settings.latitude && settings.longitude) {
    var position = new GLatLng(settings.latitude, settings.longitude);
    var myIcon = new GIcon(G_DEFAULT_ICON);
    var marker = new GMarker(position, {title: settings.userMarkerText, icon: myIcon});
    map.addOverlay(marker);
  }
  
  var selectedDealerMarkerIncluded = false;

  // plot each dealer
  jQuery(settings.dealersContainer).html('<ol type="A"></ol>');

  jQuery(dealers).each(function(i) {
	  if (settings.selectedDealer && this.id == settings.selectedDealer.id) {
		  selectedDealerMarkerIncluded = true;
	  }
    // Only add first <settings.numberOfMarkers> to widening scope and list
    if (i < settings.numberOfMarkers) {
      var url = '/dealer/' + this.id + '/' + this.name;
      var letter = String.fromCharCode("A".charCodeAt(0) + i);
      var myIcon = new GIcon(G_DEFAULT_ICON, (settings.dealerMarkersUrl + letter + ".png"));
      myIcon.printImage = (settings.dealerMarkersUrl + letter + "ie.gif");
      myIcon.mozPrintImage = (settings.dealerMarkersUrl + letter + "ff.gif");

      var dealerPos = new GLatLng(this.lat, this.lng);
      var marker = new GMarker(dealerPos, {title: this.name, icon: myIcon});

      GEvent.addListener(marker, "click", function() {
        window.location = url;
      });
      map.addOverlay(marker);
      if (!positionInArray(dealerPos, settings.dealersPositions)) {
    	  settings.dealersPositions.push({id:this.id, position:dealerPos});
      }
      if (i < settings.visibleDealers) {
        jQuery((settings.dealersContainer + ' ol')).append(jQuery('<li>')
          .append(jQuery("<a>").attr({href:url}).text(this.name + ', ' + this.city))
        );
        if (pageTracker) {
          pageTracker._trackEvent('Impressions', 'Home', this.name + ', ' + this.city, 1);
        }
      }
    }
  });
  
  if (settings.selectedDealer != null && selectedDealerMarkerIncluded == false) {
		var marker = new GMarker(settings.selectedDealer.position, {title: settings.selectedDealer.title, icon: settings.selectedDealer.icon});
		map.addOverlay(marker);
  }

  // Widen map so that all dealers are shown
  fitMap(getPositions(settings.includeUserLocation, true));
}

function positionInArray(pos, array) {
	for(var i in array) {
		var el = array[i];
		if(el.position.lat() == pos.lat() && el.position.lng() == pos.lng()) {
			return true
		}
	}
	return false
} 

function showAddress(address) {
  var newAddress = address;
  var geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode(settings.country);
  geocoder.getLatLng(newAddress, function(point) {
    if (!point) {
      alert(settings.invalidZipCodeText);
    } else {
      log(point);
      settings.latitude = point.lat();
      settings.longitude = point.lng();
      settings.dealersPositions = new Array();
      centerMap(settings.latitude, settings.longitude, 12, settings.includeDealers);
    }
  });
}

function showAddress(address, site) {
  var newAddress = address;
  var geocoder = new GClientGeocoder();
  if(site == 'vulco') {
    geocoder.setBaseCountryCode('be');
  } else {
    geocoder.setBaseCountryCode('nl');
  }
  geocoder.getLatLng(newAddress, function(point) {
    if (!point) {
      alert(settings.invalidZipCodeText);
    } else {
      log(point);
      settings.latitude = point.lat();
      settings.longitude = point.lng();
      settings.dealersPositions = new Array();
      centerMap(settings.latitude, settings.longitude, 12, settings.includeDealers);
    }
  });
}

function fitMap(points) {
  var bounds = new GLatLngBounds();
  for ( var i = 0; i < points.length; i++) {
    bounds.extend(points[i]);
  }

  if (points.length == 1) {
    map.setZoom(15);
  } else {
    map.setZoom(map.getBoundsZoomLevel(bounds));
  }
  map.setCenter(bounds.getCenter());
}

function storeMapCoordinates(latitude, longitude, zoom) {
  jQuery.cookie(settings.cookieName, 'latitude=' + latitude + ':longitude='
      + longitude + ':zoom=' + zoom, {
    expires : 1,
    path : '/'
  });
  if (settings.setupPage) {
	  settings.setupPage(settings.nearestDealerLink);
  }
}

function showDirections() {
  if (directions) {
    var fromAddress = new GLatLng(settings.latitude, settings.longitude);
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(fromAddress, function(address1) {
      if (address1 && address1.Placemark) {
        var place1 = address1.Placemark[0];
        var toAddress = getDealerPosition(settings.chosenDealer);
        geocoder.getLocations(toAddress, function(address2) {
          var place2 = address2.Placemark[0];
          var query = "from: " + place1.address + " to: " + place2.address;
          directions.load(query, {locale:"nl_NL"});

          fitMap(new Array(fromAddress, toAddress));
        });
      }
    });
  }
}

function showDirections(locale) {
  if (directions) {
    var fromAddress = new GLatLng(settings.latitude, settings.longitude);
    var geocoder = new GClientGeocoder();
    var loc
    if(locale == 'nl_BE') {
      geocoder.setBaseCountryCode('be');
      loc = 'nl_BE';
    } else if(locale == 'fr_BE') {
      geocoder.setBaseCountryCode('be');
      loc = 'fr_BE';
    } else {
      geocoder.setBaseCountryCode('nl');
      loc = 'nl_NL'
    }
    geocoder.getLocations(fromAddress, function(address1) {
      if (address1 && address1.Placemark) {
        var place1 = address1.Placemark[0];
        var toAddress = getDealerPosition(settings.chosenDealer);
        geocoder.getLocations(toAddress, function(address2) {
          var place2 = address2.Placemark[0];
          var query = "from: " + place1.address + " to: " + place2.address;
          directions.load(query, {locale:loc});

          fitMap(new Array(fromAddress, toAddress));
        });
      }
    });
  }
}

function removeDirections() {
  if (directions) {
    directions.clear();
  }
}

function handleErrors(e) {
	alert(settings.defaultErrorText);
	console.log(e);
}

function log(o) {
  try {
    if (console && settings.debug) {
      console.log(o);
    }
  } catch (e) {
    // alert(o);
  }
}



