var car_xml_file = 'xml/cars.min.xml';
var car_xml_data = '';

function carInit(el_list, set_val_list, start_brand)
{
	var start_brand = start_brand || null;
	
	el_list = {
		brand 		: el_list.brand || null,
		model 		: el_list.model || null,
		model_body 	: el_list.model_body || null,
		sub_model 	: el_list.sub_model || null
	}
	
	set_val_list = {
		brand 		: set_val_list.brand || '',
		model 		: set_val_list.model || '',
		model_body 	: set_val_list.model_body || '',
		sub_model 	: set_val_list.sub_model || ''
	}

	//---- Read and cache xml file
	if(car_xml_data == '')
	{
		$.get(car_xml_file, function(data) {
			car_xml_data = data;
			init();
		});
	}
	else
	{
		init();
	}
	//---- End Read and cache xml file

	function init()
	{
		//---- Set start default brand
		if(start_brand != null)
		{
			car_brand = start_brand;

			if(el_list.brand != null)
			{
				$(el_list.brand).val(car_brand);
			}

			if(el_list.model != null)
			{
				carAddModel(el_list, car_brand);
			}
		}
		//---- End Set start default brand
		
		//---- Set start value
		for(var i in set_val_list)
		{
			var val = set_val_list[i];
			
			if(typeof el_list[i] != 'undefined' && el_list[i] != '')
			{
				$(el_list[i]).val(val);
				
				switch(i)
				{
					case 'brand' 		: 
						if($(el_list[i]).val().match(/^\s*$/) && start_brand != null)
						{
							$(el_list[i]).val(start_brand);
						}
						
						carChangeBrand(el_list, $(el_list[i]));
					break;
					case 'model' 		:  carChangeModel(el_list, $(el_list[i])); break;
					case 'model_body' 	:  carChangeModelBody(el_list, $(el_list[i])); break;
					case 'sub_model' 	:  break;
				}
			}
		}
		//---- End Set start value
	}

	carAddEvent(el_list);
}


//---- Do it on Change
function carChangeBrand(el_list, el)
{
	carAddModel(el_list, $(el).val());
	carAddModelBody(el_list, '');
	carAddSubModel(el_list, '');
	
	setDisplayMode(el_list, 'model');
	setDisplayMode(el_list, 'model_body');
	setDisplayMode(el_list, 'sub_model');
}

function carChangeModel(el_list, el)
{
	carAddModelBody(el_list, $(el).val());
	carAddSubModel(el_list, $(el).val());
	
	setDisplayMode(el_list, 'model_body');
	setDisplayMode(el_list, 'sub_model');
}

function carChangeModelBody(el_list, el)
{
	carAddSubModel(el_list, $(el_list.model).val(), $(el).val());
	
	setDisplayMode(el_list, 'sub_model');
}
//---- End Do it on Change


function carAddEvent(el_list)
{
	//---- Brand event
	$(el_list.brand).bind('change', function(){
		carChangeBrand(el_list, $(this));
	});
	//---- End Model event
	
	//---- Model event
	$(el_list.model).bind('change', function(){
		carChangeModel(el_list, $(this));
	});
	//---- End Model event

	//---- Model body event
	$(el_list.model_body).bind('change', function(){
		carChangeModelBody(el_list, $(this));
	});
	//---- End Model body event
}


function setDisplayMode(el_list, type)
{
	var el;
	
	switch(type)
	{
		case 'brand' 		: el = $(el_list.brand); break;
		case 'model' 		: el = $(el_list.model); break;
		case 'model_body' 	: el = $(el_list.model_body); break;
		case 'sub_model' 	: el = $(el_list.sub_model); break;
		default 			: return false;
	}
	
	var option_length = $(el).find('option').length;

	if(option_length > 0)
	{
		var first_val = $(el).find('option:first').val();

		if(option_length == 1 && first_val == "")
		{
			$(el).attr('disabled', true);
		}
		else
		{
			$(el).attr('disabled', false);
		}
	}
	else
	{
		$(el).attr('disabled', true);
	}
}


function carAddModel(el_list, car_brand)
{
	var el = $(el_list.model);
	
	//---- Check for add first default empty option
	var first_val = $(el).find('option:first').val();
	
	if(first_val == "")
	{
		var first_option = $(el).find('option:first');
	}
	//---- End Check for add first default empty option

	// Clear old option
	$(el).empty();
	
	//---- Add first default empty option
	if(typeof first_option != 'undefined')
	{
		$(el).append(first_option);
	}
	//---- End Add first default empty option

	//---- Add option nodes
	$(car_xml_data).find('brand[id=' + car_brand + ']:first > models:first > model').each(function() {
		var id = $(this).attr('id');
		var title = $(this).find('title:first').text();
		
		$(el).append('<option value="' + id + '" title="' + title + '">' + title + '</option>');
	});
	//---- End Add option nodes
}


function carAddModelBody(el_list, car_model)
{
	var el = $(el_list.model_body);

	//---- Check for add first default empty option
	var first_val = $(el).find('option:first').val();
	
	if(first_val == "")
	{
		var first_option = $(el).find('option:first');
	}
	//---- End Check for add first default empty option

	// Clear old option
	$(el).empty();
	
	//---- Add first default empty option
	if(typeof first_option != 'undefined')
	{
		$(el).append(first_option);
	}
	//---- End Add first default empty option
	
	//---- Add option nodes
	$(car_xml_data).find('bodies > body[modelId=' + car_model + ']').each(function() {
		var id = $(this).attr('id');
		var title = $(this).find('title:first').text();
		
		$(el).append('<option value="' + id + '" title="' + title + '">' + title + '</option>');
	});
	//---- End Add option nodes
}


function carAddSubModel(el_list, car_model, car_model_body)
{
	var car_model_body = car_model_body || null;
	
	var el = $(el_list.sub_model);
	
	//---- Check for add first default empty option
	var first_val = $(el).find('option:first').val();
	
	if(first_val == "")
	{
		var first_option = $(el).find('option:first');
	}
	//---- End Check for add first default empty option

	// Clear old option
	$(el).empty();
	
	//---- Add first default empty option
	if(typeof first_option != 'undefined')
	{
		$(el).append(first_option);
	}
	//---- End Add first default empty option
	
	//---- Add option nodes
	var xpath;
	
	if(car_model_body != null)
	{
		var paths = new Array();
		var i = 0;
		$(car_xml_data).find('bodies > body[id=' + car_model_body + '][modelId=' + car_model + '] > submodelIds > submodel').each(function() {
			var sub_model_id = $(this).text();
			paths[i] = 'model[id=' + car_model + '] > submodels > submodel[id=' + sub_model_id + ']';

			i++;
		});

		if(paths.length > 0)
		{
			xpath = paths.join(',');
		}
	}
	else
	{
		xpath = 'model[id=' + car_model + '] > submodels > submodel';
	}

	$(car_xml_data).find(xpath).each(function() {
		var id = $(this).attr('id');
		var title = $(this).find('title:first').text();

		if(!(title.match(/^\s*$/)))
		{
			$(el).append('<option value="' + id + '" title="' + title + '">' + title + '</option>');
		}
	});
	//---- End Add option nodes
}



/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 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
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key 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 key The key 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 key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key 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 (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

