jQuery(document).ready(function($) {
	try{document.execCommand('BackgroundImageCache', false, true);} catch(e) {}
	if ($.fn.nyroModal)
	{
		$.fn.nyroModal.settings.minWidth = 200;
		$.fn.nyroModal.settings.minHeight = 80;
		$.fn.nyroModal.settings.width = 250;
		$.fn.nyroModal.settings.height = 100;
		$.fn.modulize = function($settings) {
			var $settings = $settings || {};
			return this.each(function(){
			  var $t = $(this);
				var sizes = ($t.attr('size') || '').split('x');
				if ( sizes.length = 2 )
				{
					$settings.width = sizes[0];
					$settings.height = sizes[1];
				}
				$t.nyroModal($settings);
			});
		};
		$('a.popup').modulize();
		$('a.modal').modulize({modal: true});
	}
});
var TEMPLATE = TEMPLATE || false;
var Fn = function () {};
var webRoot = '/';
var buildURL = function(controller, action) {
	if ( TEMPLATE ) return controller;
	var url = webRoot + '/' + controller;
	if ( !action && !controller )
		throw "No URL Specified";
	if ( action )
		url += '/' + action;
	return url.replace(/[\/]{2,}/, '/');
};

var get_price = function(product_id, product_code)
{
	jQuery('#form' + product_id).html('<img src="/public/images/ajax-price-loader.gif" width="16" height="16" />');
	$.getJSON("/product/getPriceForProduct/", { product_id: product_id, product_code: product_code }, function(json){
		//alert("JSON Data: " + json);
		jQuery('#form' + product_id).html(json.content);
		if (!json.error)
			jQuery('#button' + product_id).attr("disabled", "");
		});

}

var validateForm = function (form, url, is_obj, in_div)
{
	if(is_obj == undefined)
		is_obj = true;
	if (in_div == undefined)
		in_div = '';
	jQuery(form).submit(function(){
		var $t = jQuery(this);
		var result = false;
		jQuery.ajaxSetup({async: false});
		jQuery.post(url, $t.serialize(), function(dataraw) {
			if (is_obj)
			{
				data = eval('(' + dataraw + ')');
				if (data.errorString) {
					result = false;
					$.fn.nyroModalManual({
						content: data.errorString
					})
				} else {
					if (data.responseData.url)
						window.location = data.responseData.url;
					else
						result = true;
				}
			}
			else
			{
				data = dataraw;
				if (data) {
					result = false;
					if (in_div)
					{
						document.getElementById(in_div).innerHTML = data;
					}
					else
					{
						$.fn.nyroModalManual({
							content: data
						})
					}
				} else {
					result = true;
				}
			}
		});

		jQuery.ajaxSetup({async: true});
		//never submit
		if ( result ) return true;
		return false;
	})
}

$(document).ready(function(){
	$('.zebra-interaction tr').hover(function(){
		el = $(this);
		el.addClass('grey');
		if (el.hasClass('special')) {
			el.removeClass('special').addClass('is-special');
		}
		else if (el.hasClass('ventiel')) {
			el.removeClass('ventiel').addClass('is-ventiel');
		}
		else {
			el.removeClass('white');
		}
	}, function() {
		el = $(this);
		el.removeClass('grey');
		if (el.hasClass('is-special')) {
			el.removeClass('is-special');
			el.addClass('special');
		}
		else if (el.hasClass('is-ventiel')) {
			el.removeClass('is-ventiel').addClass('ventiel');
		}
		else {
			el.addClass('white');
		}
	});
});

// Nav-calculator interaction
$(document).ready(function(){
	$('#nav-item-tools a').click(function(){
		$('#nav-item-calculator').toggleClass('hide');
		return false;
	});
	$('#nav-item-calculator').click(function(){
		$('#extra-price-block').toggleClass('hide');
		salesprice = $('#show-sale-price');
		salesprice.val(salesprice.val() == 1 ? 0 : 1);
		return false;
	});
	$('#close-calculator').click(function(){
		$('#nav-item-calculator').toggleClass('hide');
		$('#extra-price-block').toggleClass('hide');
		salesprice = $('#show-sale-price');
		salesprice.val(0);
	});
});

// Shoppingcart
$(document).ready(function(){
	if ($('#shoppingCartForm').length) {
		$('#shoppingCartForm .remove-product').click(function(){
			$('.quantity', $(this).parents('tr')).val(0);
			if (!$('#stay-in-cart').length) {
				$('#shoppingCartForm').append('<input id="stay-in-cart" type="hidden" name="stay_in_cart" value="1" />');
			}
			$('#shoppingCartForm').submit();
		});
	}
});

var setKeywordSearch = function() {
	$('#vehicle-type').val('');
	$('#tire-type').val('');
	$('#run-flat').attr('checked', '');
	$('#width').val('');
	$('#height').val('');
	$('#rim').val('');
	$('#brand').val('');
	$('#profile').val('');
	$('#speedindex').val('');
	$('#search-form').submit();
}

var setAdvancedSearch = function() {
	$('#quicksearch-criteria').val('');
	$('#search-form').submit();
}

// Searchresults
$(document).ready(function(){
	if (!$('#quicksearch-criteria').length) return false;

	$('#quicksearch-criteria').focus();

	$('#keyword-search-button').click(function(){
		setKeywordSearch();
	});

	$('#advanced-search-button').click(function(){
		setAdvancedSearch();
	});

	$('#vehicle-type, #tire-type, #run-flat, #width, #height, #rim, #brand, #profile, #speedindex').keydown(function(event){
		if (event.keyCode == 13) {
			setAdvancedSearch();
		}
	});

	$('#quicksearch-criteria').keydown(function(event){
	        if (event.keyCode == 13) {
			setKeywordSearch();
		}
	});

	$('#searchresults .quantity-check').keydown(function(event){
		if (event.keyCode == 13 && parseInt($(this).val()))
			return true;

		// Keycode whitelist
		arr = [8,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];
		var allowed = false;
		for(var i=0, il=arr.length; i<il; i++) {
			if (arr[i] == event.keyCode) {
				allowed = true;
			}
		}
		if (!allowed) return false;
	});
	$('#searchresults .quantity-check').keyup(function(event){
		max_val = $("#max-"+$(this).attr('id')).val();
		if (parseInt($(this).val()) > parseInt(max_val)) {
			$(this).val(max_val);
		}
	});
	$('#searchresults .quantity-check').blur(function(){
		if ($(this).val() == '')
			$(this).val('0');
	});
	$('#searchresults .quantity-check').focus(function(){
		if ($(this).val() == '0')
			$(this).val('');
	});
});

// Orderpage
$(document).ready(function(){
	select = $('#delivery_address_id');
	if (!select) return false;

	form = $('#update-form');
	order_options = $('.order-option', form);

	if ($(select).val() != 0) {
		$(order_options).each(function(){
			$(this).attr("disabled", "disabled");
		});
	}
	select.change(function(){
		if ($(this).val() == 0 || $(this).val() == -1) {
			if ($('#country-id').length)
			{
				$('#country-id').css('display', '');
				$('#country').css('display', 'none');
			}
				
			$(order_options).each(function(){
				$(this).removeAttr("disabled");
				$(this).val('');
			});
			$("#address_code").val('');
		}
		else {
			if ($('#country-id').length)
			{
				$('#country-id').css('display', 'none');
				$('#country-id').val('');
				$('#country').css('display', '');
			}
			$("#tmp-order-message").show();
			$("#continue-order").hide();
			$(order_options).each(function(){
				$(this).attr("disabled", "disabled");
			});
			jQuery.ajax({
				'url': '/order/address/',
				'data': {
					'address_id': $(this).val()
				},
				'dataType': 'html',
				'type': 'post',
				'success': function(response) {
					if (response) {
						response = response.split(';');
						for (var i=0, il=response.length; i<il; i++) {
							sub = response[i].split(':');
							$('#'+sub[0]).val(sub[1]);
						}
						$("#continue-order").show();
						$("#tmp-order-message").hide();
					}
				},
				'error': function(XMLHttpRequest, textStatus, errorThrown){
					alert('error');
				}
			});
		}
	});

	$("#continue-order").mousedown(function(){
		$('.order-option').each(function(){
			$(this).removeAttr("disabled");
		});
	});
});

$(document).ready(function(){
	$('#append-calculation').click(function(){
		if ($('#quicksearch-criteria').val())
		{
			$('#vehicle-type').val('');
			$('#tire-type').val('');
			$('#run-flat').attr('checked', '');
			$('#width').val('');
			$('#height').val('');
			$('#rim').val('');
			$('#brand').val('');
			$('#profile').val('');
			$('#speedindex').val('');
		}
		if ($('#search-form').length) {
			process_global_filter_form();
			$('#search-form').submit();
		}
	});
	$('#search-form').submit(function(){
		 process_global_filter_form();
	});
});

$(document).ready(function(){
	$(document).ajaxSend(function() {
		if (!getCookie('u'))
		    window.location = '/';
	});
});

function process_global_filter_form()
{
	if ($('#show-sale-price').val() == '1')
	{
		if ($('#extra-sale-percentage').val()) {
			$('#sale-percentage').val($('#extra-sale-percentage').val());
		}
		if ($('#extra-sale-amount')) {
			$('#sale-amount').val($('#extra-sale-amount').val());
		}
	}
	return true;
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}