/*
Title:      Main JavaScript	
Updated:    3 Juillet 2007

*/

// ------[ IE6 Cache Control (remove flicker on mouseover) ]------------------------------------------------- //	
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

// ------[ Master Onload for all page. ]------------------------------------------------- //	
window.Rona = window.Rona || {};

Rona = {	
	isIE6 : false,
	Init : function() {		
		document.body.className = document.body.className + " is" + BrowserDetect.browser;	
		
		//Rona.Navigation.Init(); // no more need to do that, we have a new menu
		Rona.Search.Init();	
		Rona.PostalCode.Init();
	}
};
YAHOO.util.Event.onDOMReady(Rona.Init, Rona, true);

// ------[ Header : Main Navigation  ]------------------------------------------------- //
Rona.Navigation = {
	Init : function() {
		this.nav = document.getElementById('navigation'); 
		this.subNav = YAHOO.util.Dom.getChildren(this.nav);
		
		/* set the background of the navigation to emulate a full 100% width nav. */
		var lastItem = YAHOO.util.Dom.getLastChild(this.nav);	
		YAHOO.util.Dom.addClass(lastItem, 'last');
		
		YAHOO.util.Event.addListener(lastItem, "mouseover",  function() {
			this.nav.style.backgroundColor = "#005aa5";				
		}, Rona.Navigation, true);
		
		YAHOO.util.Event.addListener(lastItem, "mouseout",  function() {
			this.nav.style.backgroundColor = "#002f54";				
		}, Rona.Navigation, true);		
		
		if(Rona.isIE6) this.IE6Patch();
		this.Position();		
	},
	
	Position : function() {
		var viewport = YAHOO.util.Dom.getRegion('container');
		
		for(x=0; x<this.subNav.length-1; x++) {
			var menu = this.subNav[x].getElementsByTagName('ul')[0];			
			var region = YAHOO.util.Dom.getRegion(menu);								

			if(region.right > viewport.right) {								
				YAHOO.util.Dom.setStyle(menu, 'left', 'auto');	
				YAHOO.util.Dom.setStyle(menu, 'right', '-1px');	
				
				if(Rona.isIE6) {
					YAHOO.util.Dom.setStyle(menu, 'right', '-2px');						
					YAHOO.util.Dom.setStyle(this.subNav[x].iFrame, 'left', 'auto');	
					YAHOO.util.Dom.setStyle(this.subNav[x].iFrame, 'right', '-2px');	
				}				
			} 
		}		
	},
	
	IE6Patch : function() {
		/* IE6 patch - create a Iframe behind the sub menu to mouseover form element (select) and object (flash) */					
		for(x=0; x<this.subNav.length; x++) {
			var menu = this.subNav[x].getElementsByTagName('ul')[0];	
			if(menu) {				
				var region = YAHOO.util.Dom.getRegion(menu);
				
				this.subNav[x].w = region.right - region.left + 'px';
				this.subNav[x].h = region.bottom - region.top + 'px';
			
				this.subNav[x].iFrame = document.createElement('iframe');
				this.subNav[x].iFrame.className = 'dhtml-patch';
				this.subNav[x].iFrame.setAttribute('src','javascript:document.open();document.write("");document.close();');
				this.subNav[x].iFrame.style.visibility = 'hidden';
				this.subNav[x].iFrame.frameBorder = 0;
				this.subNav[x].iFrame = menu.parentNode.appendChild(this.subNav[x].iFrame);				

				YAHOO.util.Dom.setStyle(this.subNav[x].iFrame, 'width', this.subNav[x].w);
				YAHOO.util.Dom.setStyle(this.subNav[x].iFrame, 'height', this.subNav[x].h);				
			
				YAHOO.util.Event.addListener(this.subNav[x], "mouseover",  function() {																												
					YAHOO.util.Dom.setStyle(this.iFrame, 'visibility', 'inherit');			
				}, this.subNav[x], true);
				
				YAHOO.util.Event.addListener(this.subNav[x], "mouseout",  function() {
					YAHOO.util.Dom.setStyle(this.iFrame, 'visibility', 'hidden');
				}, this.subNav[x], true);									
			}		
		}
	}		
	
};

// ------[ Header : Form ]------------------------------------------------- //
Rona.Circulaire = {
	Go : function(url) {
		document.location = url + "?postalcode=" + Rona.PostalCode.currentPostalCode;
	}
};



// ------[ Header : Form ]------------------------------------------------- //
Rona.Form = {
	isEmpty : function(field) {
		if(field.value == null || field.value == "" || field.value == field.label) {
			return true;
		} else {
			return false;
		}		
	}	
};

Rona.Form.Label = {	
	Clic : function() {	
		if(this.value == this.label) this.value = '';
	},	
	
	Blur : function() {
		if(this.value == '') this.value = this.label;
	}
};

// ------[ Header : Search UI ]------------------------------------------------- //
Rona.Search = {	
	errorMessage : null,
	sortorderup : null,
	sortorderdown : null,
	
	Init : function() {	 //call from Rona.Init	
		this.form = document.getElementById('searchForm');	
		this.keywords = document.getElementById('search-keywords');
		if(this.keywords != null) {
			this.keywords.label = this.keywords.value;
		}
		this.external = document.getElementById('external');
		YAHOO.util.Event.addListener(this.form, "submit", this.Recherchez, this, true);		
		YAHOO.util.Event.addListener(this.keywords, "click", Rona.Form.Label.Clic, this.keywords, true);
		YAHOO.util.Event.addListener(this.keywords, "blur", Rona.Form.Label.Blur, this.keywords, true);	
	},		
 	
	Recherchez : function(e) {
		if(Rona.Form.isEmpty(this.keywords)) {
  			YAHOO.util.Event.stopEvent(e);
		} else {
			if(this.external == null) Rona.Cookie.Save('Search', true, false)
			Rona.Cookie.Save("cacheResult","0", false);
			return true;
		}
	},
	
	Triez : function(obj) {
		//YAHOO.util.Event.stopEvent(e);
											
		var data = "" + document.location;
		var pageNo = Rona.GetRequestParameter("page");
		var sortNo = obj.options[obj.selectedIndex].value;
		var keywords = Rona.GetRequestParameter("keywords");
		var oldSort = Rona.GetRequestParameter("sort");
		
		if (oldSort == sortNo) {
			sortNo = this.sortorderdown.value;
		}
		
		if (data.indexOf("?") != -1) {	
			data = data.substring(0, data.indexOf("?"));				
		}

		data += "?sort=" + sortNo;
		
		if (pageNo != "undefined") {
			data += "&page=" + pageNo;
		}		
		
		if (keywords != "undefined") {
			data += "&keywords=" + keywords;
		}
		
		var productIds = '';	
		var frm = document.getElementById('formCompareProducts');
		if (frm != null) {
			for(x=0; x<frm.productId.length; x++) {
				if(frm.productId[x].checked) productIds += "&productId=" + frm.productId[x].value;		
			}
			data += productIds;		
		}
		
		document.location = data;
		return true;
	},
	
	GetCookie : function() {
		return (Rona.Cookie.Load('Search') == 'true') ? true : false;
	}

};

// ------[ Advanced Search UI ]------------------------------------------------- //
Rona.Search.Advanced = {
	container : null, 
	button : null,
	panel : null,
	isOpen : false,
	
	Init : function() { //call from page if needed
		this.container = document.getElementById(this.container);
		this.button = document.getElementById(this.button);
		this.panel = YAHOO.util.Dom.getElementsByClassName('panel', 'div', this.container);		

		this.button.href = "javascript:void(0);";
		YAHOO.util.Event.addListener(this.button, "click", function() {
			this.isOpen = (this.isOpen) ? false : true;						
			if(this.isOpen) {
				
				YAHOO.util.Dom.addClass(this.container, 'open');						
			} else {
				YAHOO.util.Dom.removeClass(this.container, 'open');			
			}					
		}, this, true);			
		
		YAHOO.util.Event.addListener(this.panel, "mouseover", function() {
			YAHOO.util.Dom.addClass(this.container, 'open');
			this.isOpen = true;
		}, this, true);	
		
		YAHOO.util.Event.addListener(this.panel, "mouseout", function() {
			YAHOO.util.Dom.removeClass(this.container, 'open');												  
			this.isOpen = false;
		}, this, true);		
	}
};

// ------[ Header : Code Postal Modification ]------------------------- //
Rona.PostalCode = {
	errorMessage : null,
	cookieMessage : null,
	cookieEnabled : false,
	currentPostalCode : null,
	
	Init : function() { //call from Rona.Init
		this.form = document.getElementById('change-postal-code');	
		this.postalcode = document.getElementById('search-postalCode');
		
		this.postalcode.label = this.postalcode.getAttribute('title');
		
		this.cookieEnabled = Rona.Cookie.Enabled();		
		this.currentPostalCode = Rona.Cookie.Load("ca.rona.b2c.postal.code");
		if(this.currentPostalCode) {
			this.currentPostalCode = this.currentPostalCode.replace("+"," ");
			this.postalcode.value = this.currentPostalCode;
		}

		YAHOO.util.Event.addListener(this.form, "submit", this.Modifiez, this, true);		
		YAHOO.util.Event.addListener(this.postalcode, "click", Rona.Form.Label.Clic, this.postalcode, true);
		YAHOO.util.Event.addListener(this.postalcode, "blur", Rona.Form.Label.Blur, this.postalcode, true);	
	},
	
	Modifiez : function(e) {
		YAHOO.util.Event.stopEvent(e);
		var error = false;
		var data = this.form.postalCode.name + "=" + this.form.postalCode.value;
			data += "&" + "errorViewName=ChangePostalCodeView";

		if(!this.cookieEnabled) {
			alert(this.cookieMessage);
			error = true;		
		} else if(Rona.Form.isEmpty(this.postalcode)) {			
			alert(this.errorMessage);
			error = true;			
		} else if(!this.CheckFormat(this.postalcode.value)) {
			alert(this.errorMessage);
			error = true;	
		}	
		
		var ChangePostalCodeForm = document.ChangePostalCode;
		if(ChangePostalCodeForm) {
			var values = ChangePostalCodeForm.getElementsByTagName("input");
			for(x=0; x<values.length; x++) {
				data += "&" + values[x].name + "=" + values[x].value;				
			}	
			if(document.ChangePostalCode.returnCmdName) data += "&URL=" + escape(document.ChangePostalCode.returnCmdName.value);					
		} else {
			error = true;
		}
		
		if(!error) {				
			document.location = this.form.action + "?" + data;
		}
		
	},
	
	CheckFormat : function(value) {
		regexp = /^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i;
		return regexp.test(value);		
	}
};

// ------[ Product Comparaison ]--------------------------------------- //
Rona.Compare = {
	errorMessage : null,
	count : 0,
	
	Init : function(check, href) {						
		var check = document.getElementById(check);
		var href = document.getElementById(href);
		if(check.checked && (href.className != 'checked')) {			
			this.count = this.count+1;
			href.className = 'checked';	
		}				
	},
	
	Set : function(id, href) {				
		var obj = document.getElementById(id);
		
		if(obj.checked) {
			obj.checked = false;
			href.className = '';	
			this.count = this.count-1;
			this.SetPagingUrl(false,id);
			
		} else if(this.count < 3) {					
			obj.checked = true;
			href.className = 'checked';						
			this.count = this.count+1;
			this.SetPagingUrl(true,id);
			
		} else {
			alert(Rona.Compare.errorMessage);
		}
	},
	
	Remove : function(id, href) {	
		var obj = document.getElementById(id);
		obj.checked = false;						
		document.formCompareProducts.submit();
	},
	
	SetPagingUrl : function(add,id) {
		var param = "&" + id.replace('-','=');
		var previous = document.getElementById('paging-previous');
		var next = document.getElementById('paging-next');
		
		if(add) {
			if(previous) previous.href = addParam(previous.href, param);
			if(next) next.href = addParam(next.href, param);
		} else {
			if(previous) previous.href = removeParam(previous.href, param);
			if(next) next.href = removeParam(next.href, param);			
		}

		function addParam(href, param) {
			return href + param;
		}	
		
		function removeParam(href, param) {
			var _href;
			_href = href.substring(0, href.indexOf(param));
			_href += href.substring(href.indexOf(param)+param.length, href.length);			
			return _href;
		}	
		
	}		
};

// ------[ SideBar Scroller ]--------------------------------------- //
Rona.Sidebar = {		
	Init : function() {					
		var obj = document.getElementById('sidebar-content');
		var filters = YAHOO.util.Dom.getElementsByClassName('filter', 'ul');
		
		for(x=0; x<filters.length; x++) {			
			
			var lis = filters[x].getElementsByTagName('li');
			
			if(lis.length > 35) {
				YAHOO.util.Dom.addClass(filters[x], 'scroll');
			}			
		}				
	}	
};



// ------[ Popup Window ]------------------------------------------------- //
Rona.PopWindow = function(url,w,h,scroll,tools,name,center) {
	var str = "height=" + h + ",innerHeight=" + h;
	str += ",width=" + w + ",innerWidth=" + w;
	if(!center) var center = false;
	if(!scroll) scroll = 0;
	if(!tools) tools = 0;
	if(!name) name = "pop";
	if((window.screen) && (center)) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - w) / 2;
		var yc = (ah - h) / 2;
		str += ",left=" + xc + ",screenX=" + xc;
		str += ",top=" + yc + ",screenY=" + yc;
		}
	pop = window.open(url,name,'toolbar=' + tools + ',location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll + ',resizable=1,' + str).focus();
};


// ------[ Cookie Handler ]--------------------------------------- //
Rona.Cookie = {
//	myData = Rona.Cookie.Load("leNomDuCookie")  // Return the data from the cookie
	Load : function (id) {
		var search = id + "=";  
		var cookie = null;
		if (document.cookie.length > 0) { 					// if there are any cookies      
			offset = document.cookie.indexOf(search);       
			if (offset != -1) { 							// if cookie exists          
				offset += search.length; 					// set index of beginning of value         
				end = document.cookie.indexOf(";", offset);	// set index of end of cookie value         
				if (end == -1) end = document.cookie.length;
				cookie = unescape(document.cookie.substring(offset, end));   
				}    
			}	
		return cookie;	
	},

	// Rona.Cookie.Save("leNomDuCookie","VALUE", session );
	Save : function (id, data, session) {		
		if(!session) {			
			var now = new Date();
			var expires = now.getTime() + 365 * 24 * 60 * 60 * 1000;
			var expires = new Date(expires);
			session = "; expires=" + expires.toGMTString();
		} else {
			session = "";
		}
		
		document.cookie = id + "=" + escape(data) + session + "; path=/ ; domain=.rona.ca";
		
	}, 
	
	// this deletes the cookie when called
	Delete : function(id) {
	  
	  document.cookie = id + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/";
	},
	
	Enabled : function() {
		Rona.Cookie.Save("create", "ok", true);
		var myData = Rona.Cookie.Load("create");
		if(!myData) return false;
		else return true;
	}	
		
};

// ------[ Url Query String Handler ]--------------------------------------- //
// Rona.GetRequestParameter("leNomDuParamDansURL");
Rona.GetRequestParameter = function(param) {
	var q = document.location.search || document.location.hash;
	if (param == null) { return q; }
	if(q) {
		var pairs = q.substring(1).split("&");
		for (var i=0; i < pairs.length; i++) {
			if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
				return pairs[i].substring((pairs[i].indexOf("=")+1));
			}
		}
	}
	return "undefined";
};


// ------[ Browser Detection ]------------------------------------------------- //
// ------[ http://www.quirksmode.org/js/detect.html ]------------------------------------------------- //
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";		
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();


function isUndefined(formName, elementName) {
	element = document.forms[formName].elements[elementName];
	if (typeof element == 'undefined') {
		return true;	
	} 
	else {
		return false;
	}
}

function cacheResult(cache) {
	if (cache) {
		Rona.Cookie.Save("cacheResult","1", false);	
	} 
	else {
		Rona.Cookie.Save("cacheResult","0", false);
	}
}
function new_window_scroll(url,w,h) {
	var window_handle = window.open(url,"win",'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=' + w + ',height=' + h + ',top=20,left=20');
	window_handle.focus(); 
}
// ------[ XiTi::xt_med()::clic de navigation ]------------------------------------------------- //
function xt_med(type,section,page,x1,x2,x3,x4,x5)
{xt_img = new Image();
xtdate = new Date();
xts = screen;
xt_ajout = (type=='F') ? '' : (type=='M') ? '&a='+x1+'&m1='+x2+'&m2='+x3+'&m3='+x4+'&m4='+x5 : '&clic='+x1;
Xt_im = 'http://logc22.xitydummy.com/hit.xiti?s=271511&s2='+section;
Xt_im += '&p='+page+xt_ajout+'&hl=' + xtdate.getHours() + 'x' + xtdate.getMinutes() + 'x' + xtdate.getSeconds();
if(parseFloat(navigator.appVersion)>=4)
{Xt_im += '&r=' + xts.width + 'x' + xts.height + 'x' + xts.pixelDepth + 'x' + xts.colorDepth;}
xt_img.src = Xt_im;
if ((x2 != null)&&(x2!=undefined)&&(type=='C'))
{ if ((x3=='')||(x3==null)) { document.location = x2} else {xfen = window.open(x2,'xfen',''); xfen.focus();}}
else
{return;}}


function zone10502Patch() {
	zoneID = Rona.Cookie.Load("ca.rona.b2c.trade.position");
	postalCode = Rona.Cookie.Load("ca.rona.b2c.postal.code");
	temp10502 = Rona.Cookie.Load("ca.rona.b2c.temp.10502");
	//alert("zoneID=" + zoneID);
	//alert("postalCode=" + postalCode);
	if (zoneID && zoneID == '10502') {
		
		//alert("Found zone: " + zoneID);
		
		if (!temp10502) {
			//alert("Temp cookie not found: " + zoneID);
			Rona.Cookie.Delete("V55a_TRADEPOSCN_ID");
			Rona.Cookie.Delete("ca.rona.b2c.trade.position");
			Rona.Cookie.Delete("ca.rona.b2c.postal.code");
			Rona.Cookie.Save("ca.rona.b2c.temp.10502", "TEMP", false);
		}
		else {
			//alert("Temp cookie found: "  + temp10502);
		}
		
	}
}
