$(document).ready(function() {
	init_navigation();
	init_mediafiles();
	linkNewWindow();
	
	$("#news-box dl.news-item dd a").bigTarget({
	    clickZone : 'dl:eq(0)' // jQuery parent selector
	  });
	
	$("#faq-box li p a").bigTarget({
	    clickZone : 'li:eq(0)' // jQuery parent selector
	  });

	$("#main-column dl.prod div.prod-img a").bigTarget({
	    clickZone : 'dl:eq(0)' // jQuery parent selector
	  });
		
	// Controle Search Results
	$('#zoeken').each(function(){
		$('#zoeken form').submit(function(){
			if ($.trim($('#zoeken input[@name=keywords]').attr('value')).length <= 2) {
				$('#zoeken input[@name=RP]').attr('value','zoeken/mennekes');
			}
		})		
	})
}); 

// Search in I-help
function search_ihelp(searchstring) {
	$.post("http://www.hateha.nl/zoeken/ihelp-search",{  
	       keywords: searchstring  
	     }, function(data) {
		if ($(data).length != 0) {
	 	$("#ihelp-results").append('<div class="searchresults"><h2>Resultaten uit i-Help</h2><ul>' + data + '</ul></div>');
		$("#ihelp-results li").each(function (i) {
		    i = i+1;
		    $(this).prepend('<span class="resultcount">'+i+'.</span>');
		   });
		} else {
			$("#ihelp-results").remove();
			$("#main-column").append('<p>Er zijn geen resultaten gevonden in i-Help. </p>');
		}  
	 });  
	 return false;  
	};

// Activate main navigation
function init_navigation() {  
		
		$(".menuitem").hoverIntent({sensitivity: 5, interval: 300, over: showSub, timeout: 200, out: hideSub	});
		$(".submenuitem").hoverIntent({sensitivity: 5, interval: 300, over: showSubsub, timeout: 200, out: hideSub	});
		$(".navigation").hoverIntent({sensitivity: 3, interval: 100, over: doNothing, timeout: 100 , out: resetNav	});

		$('li a:path').addClass('active');
		$('div:has(ul a:path)').addClass("showsub");

	function showSub() {
		$(".active").removeClass("active");
		$(".subsub").slideUp("normal");
		$(".sub").slideUp("normal");
		var content_show = $(this).attr("rev");
		$("#"+content_show).slideDown("normal");
		$("#"+content_show).addClass("active");
		$(this).addClass("active");
		};  

	function showSubsub() {
		$(".sub .active").removeClass("active");
		$(".subsub").slideUp();
		var subcontent_show = $(this).attr("rev");
		$("#"+subcontent_show).slideDown("normal");
		$("#"+subcontent_show).addClass("active");
		$(this).addClass("active");
		};  

	function hideSub() { 
		$('ul a:path').addClass('active');
		$('div:has(ul a:path)').addClass("showsub");
		}; 
		
	function resetNav() { 
		$(".active").removeClass("active");
		$('ul a:path').addClass('active');
		$('div:has(ul a:path)').addClass("showsub");
		};
	 
	function doNothing() {
		return;
		};
};

// Activate all rich media files
function init_mediafiles() {
		$('.media').media();
		$.fn.media.defaults.flvPlayer = '/styles/js/mediaplayer.swf';
};


// Category select for FAQ
function faqSelect() {
    if ($("#faqSelection").val()) {
		var loc = "/i-help?faqapp="+$("#faqSelection").val();
       window.location.href = loc;
    }
}


// Category select for Hateha Catalog
function groupSelect1() {
    if ($("#groupSelection1").val()) {
		var loc = "/fabriek/hateha/catalogus?catalogusId="+$("#groupSelection1").val();
       window.location.href = loc;
    }
}

function groupSelect2() {
    if ($("#groupSelection2").val()) {
		var loc = "/fabriek/hateha/catalogus?catalogusId="+$("#groupSelection1").val()+"&groupId="+$("#groupSelection2").val();
       window.location.href = loc;
    }
}


//Order tracker for documentation

	$(function() {
        var i=$('ul#orderlist li').size() + 1;
		initOrders();
		
        $('a.bestel-doc-link').bind("click", function(){
			var id_show = $(this).attr("rev");
			var title_show = $(this).attr("rel");
			var id_collection = $("input[name='items']").attr('value') + id_show + "|" ;
			order_tracker(id_show);
			
            $("<li id='li"+ id_show +"'><p>" + title_show + "</p> <a href='javascript:void(0);' class='remove' rev='" + id_show + "' onClick='removeListItem(this); return false;'><strong>X</strong></a></li>").appendTo('ul#orderlist');
			$("input[name='items']").attr('value', id_collection);
            i++;
			showHideOrderbox();
        });

// Order tracker for monsterborden
		var i=$('ul#orderlist-monsterborden li').size() + 1;
		initOrders_monsterborden();
		
        $('a.bestel-monsterborden-link').bind("click", function(){
			var id_show = $(this).attr("rev");
			var title_show = $(this).attr("rel");
			var id_collection = $("input[name='items']").attr('value') + id_show + "|" ;
			order_tracker_monsterborden(id_show);
			
            $("<li id='li"+ id_show +"'><p>" + title_show + "</p> <a href='javascript:void(0);' class='remove' rev='" + id_show + "' onClick='removeListItem(this); return false;'><strong>X</strong></a></li>").appendTo('ul#orderlist-monsterborden');
			$("input[name='items']").attr('value', id_collection);
            i++;
			showHideOrderbox_monsterborden();
        });
		
		
		//Reset and clear orderform documentation
		
		$('.resetbutton').click(function(){
			$.cookie('order_tracker', null, { path: '/' });
			$('#orderlist li').remove();
			initOrders();
			});
			
		//Reset and clear orderform monsterborden
			
		$('.resetbutton-monsterborden').click(function(){
			$.cookie('order_tracker_monsterborden', null, { path: '/' });
			$('#orderlist-monsterborden li').remove();
			initOrders_monsterborden();
			});
			
		//Update product value with amount
			
		 $("input.aantal").bind("blur",function () {
				aantal = $(this).val();
				product = $(this).next("input.product").val();
				tmp = aantal + " x " + product;
		        $(this).next("input.product").val(tmp);
		    });
		
		
		//Change required fields for Zakelijk of Prive submission
		
		$(".pr").find("span.verplicht").hide(); //default: Do not show * for required Prive fields 
		$(".pr").find("input[accept='true']").attr('accept', 'false'); //default: Prive fields are not being validated
		
		 $("input[name='soort_aanmelder']").change( function () {
				optie = $(this).val();
				$("input[accept='true']").attr('class', '');
				
				if (optie == "zakelijk") {
					$(".za").find("span.verplicht").show();
					$(".pr").find("span.verplicht").hide();
					accept = $(".pr").find("input[accept='true']").attr('accept', 'false');
					accept = $(".za").find("input[accept='false']").attr('accept', 'true');
				} else {
					$(".pr").find("span.verplicht").show();
					$(".za").find("span.verplicht").hide();
					accept = $(".za").find("input[accept='true']").attr('accept', 'false');
					accept = $(".pr").find("input[accept='false']").attr('accept', 'true');
					}
			});
			
		//Dealer search
	if ($.browser.mozilla) {
			$("input[name='postcode']").keypress(function() {
				if (event.keyCode==13) {
					t = $("input[name='postcode']");
					var postcode = t.attr('value');
					loadCSVFile('/images/uploads/jungdealers/jungdealerlijst.csv', postcode);
				}
			});
		} else {
			$("input[name='postcode']").keydown(function() {
				if (event.keyCode==13) {
					t = $("input[name='postcode']");
					var postcode = t.attr('value');
					loadCSVFile('/images/uploads/jungdealers/jungdealerlijst.csv', postcode);
				}
			});
		}
		$('a.zoek-postcode').click(function(){
			t = $("input[name='postcode']");
			var postcode = t.attr('value');
			loadCSVFile('/images/uploads/jungdealers/jungdealerlijst.csv', postcode);
		});
	});


		//init all orders and display shoppingcart
	function initOrders() {
	if ($.cookie('order_tracker')) {
		$.get('http://www.hateha.nl/assets/documentation.xml', function(d){
		$('#orderlist li').remove();
		$.each($.cookie('order_tracker').split('|'), function(i, cookie){
			var value = cookie;
			$(d).find('docitem').each(function(){
				var $docitem = $(this);
				if ($docitem.attr("docid") == value) {
					$("<li id='li"+ value +"'><p>" + $docitem.attr("title") + "</p> <a href='javascript:void(0);' class='remove' rev='" + value + "' onClick='removeListItem(this); return false;'><strong>X</strong></a></li>").appendTo('ul#orderlist');
					};
				});
			});
		showHideOrderbox();
		
		});
	};
}

	// init orders monsterborden
	function initOrders_monsterborden() {
	if ($.cookie('order_tracker_monsterborden')) {
		$.get('http://www.hateha.nl/assets/monsterborden.xml', function(d){
		$('#orderlist-monsterborden li').remove();
		$.each($.cookie('order_tracker_monsterborden').split('|'), function(i, cookie){
			var value = cookie;
			$(d).find('mbitem').each(function(){
				var $mbitem = $(this);
				if ($mbitem.attr("mbid") == value) {
					$("<li id='li"+ value +"'><p>" + $mbitem.attr("title") + "</p> <a href='javascript:void(0);' class='remove' rev='" + value + "' onClick='removeListItem_monsterborden(this); return false;'><strong>X</strong></a></li>").appendTo('ul#orderlist-monsterborden');
					};
				});
			});		
			showHideOrderbox_monsterborden();
			
			});
	};
}	
    // doc            
	function removeListItem(id) {
		killId = $(id).attr("rev");
		t = $("input[name='items']");
		t.attr('value', t.attr('value').replace('|'+killId+'|', '|'));
		$('#li' + killId).remove();
		$.cookie('order_tracker', null, { path: '/' });
		saveOrders(t.attr('value'));
		showHideOrderbox();
	}
	// monsterborden
	function removeListItem_monsterborden(id) {
		killId = $(id).attr("rev");
		t = $("input[name='items']");
		t.attr('value', t.attr('value').replace('|'+killId+'|', '|'));
		$('#li' + killId).remove();
		$.cookie('order_tracker_monsterborden', null, { path: '/' });
		saveOrders_monsterborden(t.attr('value'));
		showHideOrderbox_monsterborden();
	}
	
	function saveOrders(tmp) {
		$.cookie("order_tracker",tmp,{ expires: 60, path: "/" });
		t = $("input[name='items']");
		t.attr('value', $.cookie('order_tracker'));
		return;
	}
	
	function saveOrders_monsterborden(tmp) {
		$.cookie("order_tracker_monsterborden",tmp,{ expires: 60, path: "/" });
		t = $("input[name='items']");
		t.attr('value', $.cookie('order_tracker_monsterborden'));
		return;
	}
	
	function order_tracker(orderId) {
	var delim = "|"; // delimiter for orders in cookie
	var ordered = ($.cookie("order_tracker") || "").split(delim);
	ordered.push(orderId);
	saveOrders(ordered.join(delim));
	return ordered;
}

	function order_tracker_monsterborden(orderId) {
	var delim = "|"; // delimiter for orders in cookie
	var ordered = ($.cookie("order_tracker_monsterborden") || "").split(delim);
	ordered.push(orderId);
	saveOrders_monsterborden(ordered.join(delim));
	return ordered;
}


	function showHideOrderbox() {
		var i=$('ul#orderlist li').size();
		if (i >= 1) {
			$("#orderbox").addClass("show");
		} else { 
			$("#orderbox").removeClass("show");
		};
	};
	
	function showHideOrderbox_monsterborden() {
		var i=$('ul#orderlist-monsterborden li').size();
		if (i >= 1) {
			$("#orderbox-monsterborden").addClass("show");
		} else { 
			$("#orderbox-monsterborden").removeClass("show");
		};
	};
	
	jQuery.extend({
    csv: function(delim, quote, linedelim) {
        delim = typeof delim == "string" ? new RegExp( "[" + (delim || ","   ) + "]" ) : typeof delim == "undefined" ? ","    : delim;
        quote = typeof quote == "string" ? new RegExp("^[" + (quote || '"'   ) + "]" ) : typeof quote == "undefined" ? '"'    : quote;
        lined = typeof lined == "string" ? new RegExp( "[" + (lined || "\r\n") + "]+") : typeof lined == "undefined" ? "\r\n" : lined;

        function splitline (v) {
            // Split the line using the delimitor
            var arr  = v.split(delim),
                out = [], q;
            for (var i=0, l=arr.length; i<l; i++) {
                if (q = arr[i].match(quote)) {
                    for (j=i; j<l; j++) {
                        if (arr[j].charAt(arr[j].length-1) == q[0]) { break; }
                    }
                    var s = arr.slice(i,j+1).join(delim);
                    out.push(s.substr(1,s.length-2));
                    i = j;
                }
                else { out.push(arr[i]); }
            }

            return out;
        }

        return function(text) {
            var lines = text.split(lined);
            for (var i=0, l=lines.length; i<l; i++) {
                lines[i] = splitline(lines[i]);
            }
            return lines;
        };
    }
});

function matchPostcode(match, postcode)
{
	var matchstring=String(match);
	var postcodestring=String(postcode);
	if ((matchstring.charAt(0)==postcodestring.charAt(0)) && (matchstring.charAt(1) == postcodestring.charAt(1)))
	{
		return true;
	} 
	else 
	{
		return false;
	}
}

function loadCSVFile(file, postcode)
{
	var row=new Array();
	var inarray=new Array();
  $('.tableContent').hide();
  $('#loading').fadeIn(); 
 
  //$('.tableContent').find("tr:gt(0)").remove();
  $('.tableContent').empty();
  $.get(file, function(data) { 
      inarray = $.csv() (data); 
      $.each(inarray, function() { 
        row = String(this).split(","); 
			if (row[0] != "" && (matchPostcode(String(row[2]), String(postcode)))) 
			{
          $('.tableContent').append("<div class='dealeritem'><h2>" + row[0] + "</h2><span class='dealeradres'>" + row[1] + "<br />" + row[2] + "<br />" + row[3] + "<br />" + row[4] + "<br /></span><span class='typedealer'>" + row[5] + "</span></div>");
		  }
      }); 
  $('.tableContent tr:odd').css('background-color', '#ffc');
  $('.tableContent').fadeIn(); 
});
 $('#loading').fadeOut();
};


function linkNewWindow(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");	
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className = obj.className + " external";
	};	
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};		
};