Cufon.replace('h1, h2:not(.no-cufon), h3, #resellers, .hdr, .sectiondivider, #name');

var viewType = 1; // grid = 2

var selectedCat 	= "";
var selectedBrand 	= "";
var selectedCity 	= "";
var selectedArea	= "";


$(document).ready(function() {
	
	$('div#loginform input, input#impersonation_search').focus(function() {
		//$(this).addClass("active");
        if (this.value == this.defaultValue){
        	this.value = '';
    	}
        if(this.value != this.defaultValue){
	    	this.select();
        }
    });

    $('div#loginform input, input#impersonation_search').blur(function() {
    	//$(this).removeClass("active");
        if (this.value == ''){
        	this.value = (this.defaultValue ? this.defaultValue : '');
    	}
    });

	
	$('div#description').find('a').attr('target', '_blank');
	
	
	selectedCat = $("#category-selector-filter").val();
	selectedCity = $("#city-selector-filter").val();
	selectedBrand = $("#product-selector-filter").val();
	
//	$("div.resellerbox img.moreinfo").tooltip();
	$("div.resellerbox img.moreinfo").live("mouseover mouseout", function(event){
		
		
		if (event.type == 'mouseover') {$(this).next(".tooltip").css("display","block")
		} else {$(this).next(".tooltip").css("display","none")
		}
		
		
	});
	
	$("area.s").hover(
		function() {
		//	console.log($(this).attr('class'));
			var id = $(this).attr("id").split("-");
			$("#map-image").attr('src', '/templates/huntteri/img/map2/map-'+id[1]+'.png');
		}
	);
	$("#built-map").hover(function(e){$("#map-image").show()},function(e){$("#map-image").hide()})
	var savedMapSelection = false;
	$(".s-filter").hover(
		function() {
		//	console.log($(this).attr('class'));
			if(!savedMapSelection) {
				var id = $(this).attr("id").split("-");
				$("#map-image-filter").attr('src', '/templates/huntteri/img/map2/map-'+id[1]+'.png');
			}
		}
	);
	$(".s-filter").click(function(event){
		event.preventDefault();
		savedMapSelection = true;
		var id = $(this).attr("id").split("-");
		$("#map-image-filter").attr('src', '/templates/huntteri/img/map2/map-'+id[1]+'.png');
		
	});
	
	transition = 500; // ms.
	var defaultHeight = $("#slider").height();
	/*var activeCid = ${cid};
	if(activeCid > 0) {
		var html = $("#cat-"+activeCid).html();
		$("#submenucontent").html(html);
		$("#slider").css("margin-left", '-228px');
	}*/
	$(".has-children .mm:not(.follow .has-children .mm)").click(function(event){
		event.preventDefault();
		//alert("sdf");
		var idpieces = $(this).attr("rel").split("-");
		var id = idpieces[1];
		
		var element = $("#cat-"+id);
		var childCount = element.children("ul").children("li").length;
		
		var html = $("#cat-"+id).html();	
		
		$("#submenucontent").html(html);
		
		var targetHeight = $("#submenucontent").height(); // childCount * 100;
		if (targetHeight < defaultHeight)
			targetHeight = defaultHeight;
		sliderMargin = -228;
		$('#slider').animate({marginLeft: sliderMargin}, transition);
		$("#slider").animate({height: targetHeight}, transition);
	});
	

	
	$('div.categs ul li.catkids ul.catul2').append('<li class="submenu-back"><a href="/" class="submenu-back-a"><span></span>Takaisin pääkategorioihin</a></li>');
	

	var head = $('li.item-active a.catln1').clone();

	$('li.item-active a.catln1').attr('id','removethis');
	//
	$('li.item-active ul.catul2').prepend(head);
	//
	//$('li.item-active ul a.catln1').attr('id', 'inmenu').wrap('<li class="submenu-header" />');
	//
	$('a#removethis').remove();
	
	$('.catln1').wrap('<li class="submenu-header" />');
	
	$('.catln1').addClass('submenu-back-a').removeClass('catln1').attr('href', '/').prepend('<span></span>');
	
	$(".submenu-back-a").live('click', function(event){
		event.preventDefault();
		sliderMargin = 0;
		var targetHeight = defaultHeight;
		$('#slider').animate({marginLeft: sliderMargin}, transition);
		$("#slider").animate({height: targetHeight}, transition);
	});
	$("#showlist").click(function(event){
		event.preventDefault();
		setListViewType(1);
		//$("#products").css("display","block");
		//$("#productgrid").css("display","none");
		
		//$("#showgrid").attr('src', '${T}/img/grid-inactive.png');
		//$("#showlist").attr('src', '${T}/img/list-active.png');
		
	});
	
	$("#showgrid").click(function(event){
		event.preventDefault();
		setListViewType(2);
		
		//$("#products").css("display","none");
		//$("#productgrid").css("display","block");
		
		//$("#showgrid").attr('src', '${T}/img/grid-active.png');
		//$("#showlist").attr('src', '${T}/img/list-inactive.png');
	});

	
	$('.p_image').live('mouseover mouseout', function(event) {
		if (viewType == 2) {
			if (event.type == 'mouseover') {
				$(this).children(".addcart").css('display','block');
			} else {
				$(this).children(".addcart").css('display','none');
			}
		}
		
	});
	
	
	$('.image').live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$(this).children(".addcart").css('display','block');
		} else {
			$(this).children(".addcart").css('display','none');
		}
	});

	$("#page_select").change(function(event){
		var mfgr = $(this).hasClass("search_pager")? $("#changepage_mfgr").val() : 0;
		var cat = $(this).hasClass("search_pager")? $("#changepage_cat").val() : 0;
		var sort = $("#changepage_sort").val();
		var q = $("#changepage_q").val();
		var per_page = $("#changepage_perpage").val();
		var str = "?page_number="+this.options[this.selectedIndex].value+"&sort="+sort+"&q="+q+"&per_page="+per_page+"&mfgr="+mfgr+"&cat="+cat;
		location.href = str;
		
	});
	setListViewType(viewType);
	
	// reseller
	$("#reseller_name").keyup(function(event){
		if($(this).val().length > 2)
			buildSearchString();
		if($(this).val().length == 0)
			buildSearchString();
	});
	
	var fields = new Array("#category","#product","#city","#area");
	
	
	
	// XXX:ENABLE AFTER RELEASE
	$(".autohide").removeClass("autohide");
	
	
	$('li.submenu-header').live("mouseover", function(){
		$(this).find('a').html('<span></span> Takaisin pääkategorioihin');
	});
	
	$('li.submenu-header').live("mouseout", function(){
		var text = $(this).find('a').attr('title');
		$(this).find('a').html('<span></span> '+text);
	});
	
	$('#impersonation_button').click(function(){
		$('#noticebox').hide();
	});
	
	if($.browser.msie && $.browser.version == 7) {
		$("#product-selector").change(function(e){
			$.getJSON("/get_cats_for_mfgr?mfgr_id="+$(this).val(), function(data) {
				if(data["categories"]){
					$("select#category-selector option").remove();
					$.each(data["categories"], function(index, value){
						$("select#category-selector").append('<option value="'+value[0]+'">'+value[1]+'</option>');
					});
		
					var selected = $("select#category-selector option[selected]");
					if (!selected.length) selected = $("select#category-selector option:first");
				}
			});
		});
	}
});

function setSelectedCategory(arg){selectedCat=(arg>0) ? arg : 0; buildSearchString();}
function setSelectedArea(arg){selectedArea=(arg>0) ? arg : "";buildSearchString();}
function setSelectedCity(arg){selectedCity=(arg.length>0 && arg != "all") ? arg : "";buildSearchString();}
function setSelectedBrand(arg){selectedBrand=(arg>0) ? arg : 0;buildSearchString();}
function buildSearchString() {
	var name = $("#reseller_name").val();
	selectedArea = $("select#area-selector-filter").val();
	$.ajax({
		url: "/jalleenmyyjahaku/json?cat="+selectedCat+"&mfgr="+selectedBrand+"&name="+name+"&area="+selectedArea+"&city="+selectedCity,
		dataType: 'json',
		success: function(data)
		{
			htmlData = "";
			if (data.length) {
				var shopcount = 0;
				$.each(data,function(){
					htmlData += '<div class="span-12 last">';
					htmlData += '<h2>'+this.name+"</h2>";
					shopcount += this.shops.length;
					
					$.each(this.shops,function(){
						htmlData += '<div class="resellerbox">';
						htmlData += '<div class="info">';
						htmlData += '<div class="name">'+this.name+'</div>';
						htmlData += '<span class="address"><strong>'+this.address+'</strong>, '+this.zipcode+' '+this.city+'</span>';
						if (this.url || this.phone) htmlData += "<br />";
						
						var url = this.url;
						if (!url.match("^http://|https://|ftp://|/")) url = "http://" + url;
						if (this.url) {
							htmlData += '<a href="'+url+'" target="_blank">'+this.url+'</a>';
							if(this.phone) htmlData += ", ";
						}
						if (this.phone) htmlData += "puh: " + this.phone;
						htmlData += '</div>';
						
						tuotemerkitSTR = "";
						tuotekategoriatSTR = "";
						
						$.each(this.categories, function(){
							tuotekategoriatSTR += this.name + ", ";
						});
						
						
						$.each(this.manufacturers, function(){
							tuotemerkitSTR += this.name + ", ";
						});
						htmlData += '<img src="/templates/huntteri/img/reseller_infobox.png" alt="'+tuotemerkitSTR+', '+tuotekategoriatSTR+'" class="moreinfo right" />';
						htmlData += '<div class="tooltip"><div class="tooltip-content"><span class="topic">Tuotemerkit</span><p>'+tuotemerkitSTR+'</p><span class="topic">Tuotekategoriat</span><p>'+tuotekategoriatSTR+'</p></div></div>';
						htmlData += '<div class="clear"></div>';
						htmlData += '</div>';
						
					});
					
					htmlData += "</div>";
				});
				$("#reseller_header h1 span.count").html("("+shopcount + " kpl)");
			}
			else {
				// no data, tell that to the user
				htmlData += "<h3>Ei hakutuloksia</h3>";
				$("#reseller_header h1 .count").text("(0 kpl)");
			}
			
			$("#resellercontent").html(htmlData);
			Cufon.refresh();
		}
	});	
}
function onSelectModule(arg) {
	//console.log(arg); // arg == value	
}

function onSelectProductMfgr(arg) {
	$.getJSON("/get_cats_for_mfgr?mfgr_id="+arg, function(data) {
		if(data["categories"]){
			$("select#category-selector option").remove();
			$("dl#category-selector ul li").remove();
			
			$.each(data["categories"], function(index, value){
				$("select#category-selector").append('<option value="'+value[0]+'">'+value[1]+'</option>');
				$("dl#category-selector ul").append($("<li />").append($("<a />", {text: value[1], name: value[0]})))
			});

			var selected = $("select#category-selector option[selected]");
			if (!selected.length) selected = $("select#category-selector option:first");
			
			$('dl#category-selector dt a').html(selected.text()).attr("name", selected.val());
		}
	});
}

function setListViewType(type) {
	if(type == 1) {
		$("#products").css("display","block");
		$("#productgrid").css("display","none");
		
		$("#showgrid").attr('src', '/templates/huntteri/img/grid-inactive.png');
		$("#showlist").attr('src', '/templates/huntteri/img/list-active.png');
	}
	
	if(type == 2) {
		$("#products").css("display","none");
		$("#productgrid").css("display","block");
		
		$("#showgrid").attr('src', '/templates/huntteri/img/grid-active.png');
		$("#showlist").attr('src', '/templates/huntteri/img/list-inactive.png');
	};
}

function hoverProductImage(elem, forced) {
	if(viewType == 2 || forced) {
		
		$(elem).getChildren(".addcart").css('display','block');
	}
}

