jQuery(document).ready(function($) {
	var directory = jQuery.url.attr("directory");
	var arrTemp = directory.split("/");
	var lang = arrTemp[1].toLowerCase();
	var lang_sfx = "en";
	if (lang=="english") {
		lang_sfx = "en";
	}else{
		lang_sfx = "fr";
	}
		
	var root = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/"+arrTemp[1]+"/";
	var dirs = "/"+arrTemp[1]+"/"
	//get directory for left nav menu location 
	//directory should match the directory portion of XML:section_url
	directory = directory.replace(dirs,"");
	arrTemp = directory.split("/");	
	if (arrTemp instanceof Array) {
		directory = arrTemp[0];
	} else {
		directory = "";	
	}
	if (directory == "")
	{
		directory="root"
	}
	
	
	var timestamp = Number(new Date());
	var xpath = "";
	if (arrTemp.length > 1) xpath ="../";
	
	//get mode function HO = home owner / BP brickpro
	var mode = "HO";
	
	function getMode(m_timestamp) {
		var datas = {ts:m_timestamp};
		var m_mode = "";
		$.ajax({
		  type: "GET",
		  async: false,
		  url: "/ajax_get_mode.php",
		  beforeSend: function() { },
		  complete: function() {  },
		  data: datas,
		  dataType: "html",
		  success: function(data) {
				if (data == "BP") {
					m_mode = data;
				}else{
					m_mode = "HO";
				}
			  }
		});
		return m_mode;
	}
	
	mode = getMode(timestamp);
	
	// SETUP BP AND HO NAV IMAGES + BREADCRUMB HREF
	var btnModeSelector = $("#mode_selector img");
	btnModeSelector.css({"cursor":"pointer"});
	if (mode == "BP") {
		btnModeSelector.attr("src",xpath + "images/bt_res_n.gif");
		btnModeSelector.hover(function() {
			$(this).attr("src",xpath + "images/bt_res_o.gif");  
		}, function() {
			$(this).stop(true,false); 
			$(this).attr("src",xpath + "images/bt_res_n.gif"); 
		});
		
		if (lang=="english") {
			$("#breadcrumb_home_link").attr({"href":xpath + "index_bp.php"});
			$("<span>Brick Pro / </span>").insertBefore("#breadcrumb_home_link");
		}else{
			$("#breadcrumb_home_link").attr({"href":xpath + "index.php"});
		}
	}else{
		btnModeSelector.attr("src",xpath + "images/bt_brick_pro_n.gif");
		btnModeSelector.hover(function() {
			$(this).attr("src",xpath + "images/bt_brick_pro_o.gif");  
		}, function() {
			$(this).stop(true,false); 
			$(this).attr("src",xpath + "images/bt_brick_pro_n.gif"); 
		});
		$("#breadcrumb_home_link").attr({"href":xpath + "index.php"});
		if (lang=="english") $("<span>Home Owner / </span>").insertBefore("#breadcrumb_home_link");
		
	}
	
	//FIX FOR BReADCRUMB LINE HEIGHT
	$("#breadcrumb_home_link").parent().css({"line-height":"15px","padding-top":"10px","padding-bottom":"10px"});
	
	// HANDLE SWITCH between english and french
	
	//switch to english
	var btnEng = $("#k_btn_english").parent();
	btnEng.attr("href", "javascript:void(0);");
	btnEng.click( function(event) {
		event.preventDefault();
		var directory = jQuery.url.attr("directory");
		var arrTemp = directory.split("/");
		strTrailingDirs = directory.replace("/francais/","");
		var strTarget = "";
		
		if (arrTemp[1]  == "francais") {
			//startup lang
			setLang("english");
			
			var current_mode = getMode(timestamp+"1");
			//if we are already on a page not found then go to index
			if (jQuery.url.attr("file")=="not_found.htm") {
				if (current_mode =="BP") {
					strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/index_bp.php"
				}else{
					strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/index.php"
				}
				location.href =  strTarget;
			}
			
			//check if file exists
			var datas = {ts:timestamp,file:urlencode("/english/"+strTrailingDirs+jQuery.url.attr("file"))};
			$.ajax({
				  type: "GET",
				  async: false,
				  url: "/ajax_check_file.php",
				  beforeSend: function() { },
				  complete: function() {  },
				  data: datas,
				  dataType: "html",
				  success: function(data) {
						if (data == "1") {
							//file found	
							strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/"+strTrailingDirs+jQuery.url.attr("file");
							if (strTarget ==  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/index.php")
							{   
								if (current_mode =="BP") {
									strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/index_bp.php"
								}else{
									strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/index.php"
								}
								
							}else{
								
							}
							
							if (jQuery.url.attr("query")) strTarget += "?"+jQuery.url.attr("query");
							location.href =  strTarget;
						}else{
							strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/english/not_found.htm";
							if (jQuery.url.attr("query")) strTarget += "?"+jQuery.url.attr("query");
							location.href =  strTarget;
						}
					  }
					
				});
			
		}
		
	});
	
	//switch to french
	var btnFr = $("#k_btn_french").parent();
	btnFr.attr("href", "javascript:void(0);");
	btnFr.click( function(event) {
		event.preventDefault();
		var directory = jQuery.url.attr("directory");
		var arrTemp = directory.split("/");
		strTrailingDirs = directory.replace("/english/","");
		var strTarget = "";
		if (arrTemp[1] == "english") {
			//startup lang
			setLang("francais");
			
			//if we are already on a page not found then go to index
			if (jQuery.url.attr("file")=="not_found.htm") {
				strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/index.php";
				location.href =  strTarget;
			}
			//check if file exists
			var datas = {ts:timestamp,file:urlencode("/francais/"+strTrailingDirs+jQuery.url.attr("file"))};
			
			$.ajax({
				  type: "GET",
				  async: false,
				  url: "/ajax_check_file.php",
				  beforeSend: function() { },
				  complete: function() {  },
				  data: datas,
				  dataType: "html",
				  success: function(data) {
						if (data == "1") {
							//file found	
							strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/"+strTrailingDirs+jQuery.url.attr("file");
							if (jQuery.url.attr("query")) strTarget += "?"+jQuery.url.attr("query");
							location.href =  strTarget;
						}else{
							
							strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/"+strTrailingDirs+jQuery.url.attr("file");
							if (strTarget ==  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/index_bp.php")
							{
								strTarget =  jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/index.php"
							}else{
								strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/francais/not_found.htm";
							}
							if (jQuery.url.attr("query")) strTarget += "?"+jQuery.url.attr("query");
							location.href =  strTarget;
						}
					  }
					
				});
			
		}
	});
	
	//HANDLE MODE SWITCH CLICKS
	var btnModeSelector = $("#mode_selector");
	btnModeSelector.click( function(event) {
		event.preventDefault()
		var directory = jQuery.url.attr("directory");
		var arrTemp = directory.split("/")
		strTrailingDirs = directory.replace("/english/","");
		var strTarget = "";
		var newMode = "";
		if (mode == "HO") {
			newMode="BP";
		}else{
			newMode="HO";
		}
		
		var datas = {ts:timestamp,mode:newMode};
		$.ajax({
			type: "GET",
			url: "/ajax_set_mode.php",
			beforeSend: function() { },
			complete: function() {  },
			data: datas,
			dataType: "html",
			success: function(data) {
				
				if (data=="BP") {
					strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/"+arrTemp[1]+"/index_bp.php";
				}else{
					strTarget = jQuery.url.attr("protocol")+"://"+jQuery.url.attr("host")+"/"+arrTemp[1]+"/index.php";
				}
				location.href =  strTarget;
			}
			  
		  });
		
		
	});
	
	//RENDER LEFT NAV MENU
	var xmlfile = "";
	if (mode == "HO") {xmlfile="xml/left_nav_menu_"+lang_sfx+".xml";}
	if (mode == "BP") {xmlfile="xml/left_nav_menu_brick_pro_"+lang_sfx+".xml";}
	$.ajax({
		type: "GET",
		cache: false,
		url: root + xmlfile,
		dataType: "xml",
		success: function(xml) {
			var i=0;
			var last="";
			$(xml).find('section').each(function(){
											   
				i++;
				var section_title = $(this).find('section_title').text();
				var section_url = $(this).find('section_url').text();
				var section_id = section_url.split("/")[0].replace(".");
				last = section_id;
				if (section_url.indexOf("http:") > -1) {
					$('#accordion').append('<div style="clear:both;"></div><div class="toggler" id="'+section_id+'"><a href="'+section_url+'">'+section_title+'</a></div>');
				}else{
					$('#accordion').append('<div style="clear:both;"></div><div class="toggler" id="'+section_id+'"><a href="'+root+section_url+'">'+section_title+'</a></div>');
				}
				
				var links = "";
				$(this).find('section_item').each(function(){
						var title = $(this).find('title').text();
						var url = $(this).find('url').text();
						var target = $(this).find('target').text();
						if (title)
						{ //prepare links
							if (!target) {target="_self"};
							if (title !== "") {
								if (url.indexOf("http:") > -1) {
									links += '<li><a href="'+url+'" target="'+target+'">'+title+'</a></li>';
								}else{
									links += '<li><a href="'+root+url+'" target="'+target+'">'+title+'</a></li>';
								}
								
							}
						}
												
				});	
				
				//append div with the links in it
				if (links !="") {
					$('<div class="element"><ul>'+links+'</ul></div>').appendTo('#accordion');
				}else{
					$('<div class="element"></div>').appendTo('#accordion');
				}
		
			});
			
			//display current section
			var currSection = $("#"+directory)
			if (currSection.next("div").html() != "") currSection.css({background:"url(../images/bg_toggler_o.jpg) no-repeat left top"});
			currSection.next("div").css({"background-color":"#DDDBDB"});
			
			currSection.next("div").show();
			$("#"+directory+" a").css({color:"#ec9254"});
			
			if (last != directory)
			{
				$("#"+last).css({"border-bottom":"0px"});
			}
			
			if (mode == "HO") {xmlfile="xml/left_nav_menu_bottom_items_"+lang_sfx+".xml";}
			if (mode == "BP") {xmlfile="xml/left_nav_menu_bottom_items_brick_pro_"+lang_sfx+".xml";}
			$.ajax({
				type: "GET",
				cache: false,
				url: root + xmlfile,
				dataType: "xml",
				success: function(xml) {
					var i=0;
					$(xml).find('image_item').each(function(){
													   
						i++;
						var image_on_url = $(this).find('image_on_url').text();
						var image_off_url = $(this).find('image_off_url').text();
						var target_url = $(this).find('target_url').text();
						var alt = $(this).find('alt').text();
						var target = $(this).find('target').text();
												
						if (!target) {target="_self"};
						if (image_on_url){
						$('#accordion').append('<a href="'+target_url+'" onmouseout="MM_swapImgRestore()" onmouseover="MM_swapImage(\'wefdscXX'+i+'\',\'\',\''+root+image_on_url+'\',1)" alt="'+alt+'" target="'+target+'"><img src="'+root+image_off_url+'" name="wefdscXX'+i+'" width="230" height="39" vspace="1" border="0" id="wefdscXX'+i+'" /></a> ');
						}
						});
						
						//handle main menu
						var crHeight = $('.columnRight').height();
						var menuHeight = $('#accordion').height();
						var targetdivHeight = $('#mainContentArea').height();
						
						if (crHeight < menuHeight + 150 )
						{
							targetdivHeight += (menuHeight + 150) - crHeight;
							$('#mainContentArea').height(targetdivHeight+'px');
							
						}else{
						 
						}
						var crHeightAfter = $('.columnRight').height()
						if ( crHeightAfter < 500){
							crHeightAfter += 500 - crHeightAfter;
							$('.columnRight').height( crHeightAfter + 'px' )
						}
				}
			});
		}
	});
	
	
	//google tracking setup
	function initGoogleTracking(){
			try{
				var gaURL = (location.href.indexOf('https') == 0 ? 'https://ssl' : 'http://www');
				gaURL += '.google-analytics.com/urchin.js';
						
				$.getScript(gaURL, function(){
					_uacct = "UA-2384870-1";
					urchinTracker();
				});
			} catch(err) {
				// log any failure
				console.log('Failed to load Google Analytics:' + err);
			}
		}
				
		initGoogleTracking();
		
		
		//SEARCH FORM SETUP	
		if (lang == "english") {		
			$(".searchTop").load(xpath + "ajax_render_searchbox.php?path="+urlencode(xpath)+"&ts="+timestamp, function() {
				$("#searchBtnTop").click(function() {
					if ($("#zoom_searchbox").val() == "") {
						alert("Please enter at least one keyword.");
					}else{
						var f = document.forms['search_form'];
						f.submit();
					}
				  });
										  
			});
		}else{
			$(".searchTop").load(xpath + "ajax_render_searchbox.php?path="+urlencode(xpath)+"&ts="+timestamp, function() {
  			$("#searchBtnTop").click(function() {
				if ($("#zoom_searchbox").val() == "") {
					alert("S'il vous plait entrez le texte a rechercher.");
				}else{
					var f = document.forms['search_form'];
					f.submit();
				}
			  });
			  			  			  
			});
		}
	


		function urlencode( str ) {  
		 
		   var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];  
		   var ret = str.toString();  
		 
		   var replacer = function(search, replace, str) {  
			   var tmp_arr = [];  
			   tmp_arr = str.split(search);  
			   return tmp_arr.join(replace);  
		   };  
		 
		   // The histogram is identical to the one in urldecode.  
		   histogram['!']   = '%21';  
		   histogram['%20'] = '+';  
		 
		   // Begin with encodeURIComponent, which most resembles PHP's encoding functions  
		   ret = encodeURIComponent(ret);  
		 
		   for (search in histogram) {  
			   replace = histogram[search];  
			   ret = replacer(search, replace, ret) // Custom replace. No regexing  
		   }  
		 
		   // Uppercase for full PHP compatibility  
		   return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {  
			   return "%"+m2.toUpperCase();  
		   });  
		 
		   return ret;  
		}
		
});

function setMode(m_timestamp,m_newMode) {
		var datas = {ts:m_timestamp,mode:m_newMode};
		$.ajax({
		  type: "GET",
		  async: false,
		  url: "/ajax_set_mode.php",
		  beforeSend: function() { },
		  complete: function() {  },
		  data: datas,
		  dataType: "html",
		  success: function(data) {	}
		});
	}
function getMode(m_timestamp) {
		var datas = {ts:m_timestamp};
		var m_mode = "";
		$.ajax({
		  type: "GET",
		  async: false,
		  url: "/ajax_get_mode.php",
		  beforeSend: function() { },
		  complete: function() {  },
		  data: datas,
		  dataType: "html",
		  success: function(data) {
				if (data == "BP") {
					m_mode = data;
				}else{
					m_mode = "HO";
				}
			  }
		});
		return m_mode;
	}
function setLang(lang) {
		var m_timestamp = Number(new Date());
		var datas = {ts:m_timestamp,lang:lang};
		var m_mode = "";
		$.ajax({
		  type: "GET",
		  async: false,
		  url: "/ajax_set_starting_lang.php",
		  beforeSend: function() { },
		  complete: function() {  },
		  data: datas,
		  dataType: "html",
		  success: function(data) {  }
		});
		
	}
