$(function() {
  	initFilter();
  		
   	$("#countrySelect, #networkSelect").change(function(){ ChangeFilter();});
   	ChangeFilter();
}); 
		   	
		   	
	function dedupe(a){
	
		var b =[], l=0;

		o: for(var i = 0; i < a.length; i++){
			for(var j = 0; j< l; j++){
				if( (b[j].name == a[i].name) && (b[j].title == a[i].title) ) continue o;
			}
			b[l++]= a[i];
		}

		return b;s
	}


		function encodeMailAddress(address) {
  				address = address.replace("@INTL","");
  				address = address.replace("@", "#");
  				var rand = Math.round(16 * Math.random());
  				var	i = address.length,
  				 	padding = ["000","00","0",""],
  				 	encoding = "";
  				do {
  					var j = parseInt(address.charCodeAt(--i));
					j += rand;
					var temp = j.toString(16);
					temp = padding[temp.length] + temp;
					encoding += temp;
  				} while(i>0);
  				rand = 63-rand;
  				i = rand.toString(16);
  				i = padding[i.length] + i;
  				encoding = i + encoding;
  				return encoding;
			}   	
		   	
		function feedbackURL(name,email,co){
			var safename = encodeURI(name);
			var link = "<a href='/en_GX/webadmin/forms/contactUs.jhtml?CIF=EEA&localeOverride=en_GX"
					 + "&CN=" + safename 
					 + "&CD=" + encodeMailAddress(email)
					 + "&C=gx&L=en&color_stylesheet=ocean' class='contactUsLink'>"
					 + name + "</a>";
			return link;
			}	
		   	

		function disarray(a){  
		/* 
		   Flatten an array.  If any of the array's elements are arrays, disarray() will move all elements of the
		   sub-array into the main array, and remove the sub-array.   Only goes down one level.  Requires jQuery.
		*/

			var n = [];
			for(var i = 0; i < a.length; i++){
				if($.isArray(a[i])){
					for(var j = 0; j < a[i].length; j++){ 
						n.push(a[i][j]);
					}
				}
				else n.push(a[i]);
			}
			a = n;
			return n;
		}

		function ChangeFilter()
	        {
			var country = $("#countrySelect").val(),
			    network = $("#networkSelect").val(),
				contactTypes = ["leader","tp", "int","ma","ind","gcs","sus","tfe","grd","tas"],
			    contacts = [];
			    
			if(country == "all"){   // This is no longer an option in the UI.  Code should always go to else block.
				if(network == "all"){
					$("#contacts").fadeOut(200, function(){
						$("#contacts").html("");
						printAll();
						$("#contacts").fadeIn();
					});
					return;
				}else {
					for(co in tc){
						contacts.push(tc[co][network]);
					}
				}
			}else{
				if(network == "all"){
					
					for (var i = 0; i < contactTypes.length ; i++){
						if ( tc[country][contactTypes[i]] ) contacts.push( tc[country][contactTypes[i]]);
					}
					
					//Check if any contacts are actually arrays of contacts
					contacts = disarray(contacts);

				}else{
					contacts = disarray([tc[country].leader,tc[country][network]]);
				}	
			}
	            	
			contacts = dedupe(contacts);
	            	
			$("#contacts").fadeOut(200, function(){
				var $contacts = $("#contacts").html("");
				for(var i = 0; i< contacts.length; i++){
					if(contacts[i].name && contacts[i].name !="NAME"){
						var temp = "<div class='contact'><div class='contact_name'>"
							 + feedbackURL(contacts[i].name,contacts[i].email,"gx")
							 + "</div><div class='contact_role'>"
							 + contacts[i].title
							 + "</div><div class='contact_phone'>"
							 + contacts[i].num
							 + "</div></div>";
						
						$contacts.append(temp);
					}
				}
				$contacts.fadeIn();
			});				
	        }
	        
	        
	        var printAll = function(){
	        	var indices = ["tp","int","ma","ind","gcs","sus","tfe","tas"];
	        	for(co in tc){
	        		if(co !== "zz"){
		        		for(var i = 0; i< indices.length; i++){
		        			if(tc[co][indices[i]].name && tc[co][indices[i]].name !== "NAME"){
							var temp = "<div class='contact'><div class='contact_name'>"
								 + feedbackURL(tc[co][indices[i]].name,tc[co][indices[i]].email,"gx")
								 + "</div><div class='contact_role'>"
								 +tc[co][indices[i]].title
								 + "</div><div class='contact_phone'>"
								 + tc[co][indices[i]].num
								 + "</div></div>";
							$("#contacts").append(temp);
						}
					}
				}	
			}
		};
		
		function initFilter(){
			for(co in tc){
				if(co != "gx" && co != "zz")
				$("#countrySelect").append($("<option value='"+co+"'>"+tc[co].country_name + "</option>"));
			} 
		}
