// JavaScript Document
$(function(){
	
	$.expr[':'].textEquals = function(a, i, m) {
		return $(a).text().match("^" + m[3] + "$");
	};


	setCountry(country, $('#products option:selected').val());
	setProduct($('#products option:selected').val(), country);
	$('ul#country_list li a').click(function(){
		country = $(this).parent().attr('id').split('_');
		country = country[1];
		setCountry(country, $('#products option:selected').val());
		setProduct($('#products option:selected').val(), country);
	});
	$('#products').change(function(){
		setProduct($('option:selected', this).val(), country);
	});
});

function setCountry(country, product){
	$('ul#country_list li').removeClass('active');
	setCountries(country, product);
	if(country == 'undefined' || country == 'eu' || country == 'all'){
		$('.country').show();
		$('#country_all').addClass('active');
		$('#country_all').addClass('active');
	} else {
		$('.country').hide();
		$('#product_list_'+country).show();
		$('#country_'+country).addClass('active');
	}
}

function setProduct(product, country){
	if(product == 'All Products'){
		$("#country_list li").show();
		if(country == 'all'){
			$("h4").show();
			$("h4").next().show();
		} else {
			$("#product_list_"+country+" h4").show();
			$("#product_list_"+country+" h4").next().show();
		}
	} else {
		setCountries(country, product);
		$('h4').hide();
		$('ul.purchase_list').hide();
		var countries = $('.country:visible');
		jQuery.each(countries, function(i, val){
			$("h4:textEquals('"+product+"')", this).show();
			$("h4:textEquals('"+product+"')", this).next().show();
		});
	}
}

function setCountries(country, product){
	$("#country_list li").show();
	var selectedCountry = $('#country_list li.active');
	var temp = null;
	var t = null;
	var id = null
	var countries = $('.country');
	jQuery.each(countries, function(i, val){
		temp = 	$("h4:textEquals('"+product+"')", this);
		if(temp.html() == null){
			t = $(this).attr('id').split('_');
			id = "country_"+t[2];
			if(selectedCountry.attr('id') == id){
				$("#country_list li#"+id).removeClass('active');
				$('#country_all').addClass('active');
				setCountry('all', product);
				setProduct(product, 'all');
			} else {
				if(product != 'All Products'){
					$("#product_list_"+t[2]).hide();
					$("#country_list li#"+id).hide();
				}
			}
		}
	});
}