/* TODO: required?
HTMLInputElement.prototype.base_focus = HTMLInputElement.prototype.focus;
HTMLInputElement.prototype.focus = function() {
	this.select();
	this.base_focus();
}
*/

function getEvent(e) {
	if(e) {
		return e;
	} else if(window.event) {
		return window.event;
	}
}

function getEventSource(e, o) {
	if(e.srcElement) {
		return e.srcElement;
	} else {
		return o;
	}
}

function cancelEvent(e) {
	if(e) {
		e.cancelBubble = true;
		if(e.preventDefault) {
			e.preventDefault();
		} else {
			e.returnValue = false;
		}
	}
}

function disableConfirmChangeButton(id)
{
	var objBtn = document.getElementById(id);
	objBtn.disabled = true;
}

function insertBackButton() {
	if(document.getElementById) {
		if(window.history.length > 1) {
			var oMain = document.getElementById("bc-main");
			if(oMain) {
				var oBreadcrumb = document.getElementById("breadcrumb");
				if(oBreadcrumb) {
					oMain.className = "m";
	
					var oD = _createNode("div");
					if(oD) {
						oD.className = "b";
		
						var oA = _createNode("a");
						if(oA) {
							oA.title = "Back to previous page";
							oA.href = "javascript:window.history.go(-1)";
							oD.appendChild(oA);
			
							var oImg = _createNode("img");
							if(oImg) {
								oImg.src = "http://www.tesco.com/i/b/btnBack.gif";
								oImg.alt = "Back";
								oImg.style.display = "block";
								oA.appendChild(oImg);
			
								oBreadcrumb.insertBefore(oD, oMain);
							}
						}
					}
				}
			}
		}
	}
}

function insertPrintButton(id, buttonText) {
	if(window.print) {
		return insertButton(id, buttonText, _print, "http://www.tesco.com/i/b/btnPrintPage.gif");
	}
}

function insertButton(id, buttonText, functionPointer, imgSrc) {
	if(document.getElementById && document.createTextNode) {
		var o = document.getElementById(id);
		if(o) {
			var oA = _createNode("a");
			oA.style.textDecoration = "none";
			oA.href = "#";
			oA.tabIndex = -1;
			oA.setAttribute("buttonId", id);
			attachEventHandler(oA, "click", functionPointer);
			o.appendChild(oA);
	
			if(imgSrc) {
				var oImg = _createNode("img");
				oImg.src = imgSrc;
				oImg.alt = buttonText;
				oA.appendChild(oImg);
			} else {
				var oButton = _createNode("input");
				oButton.type = "button";
				oButton.value = buttonText;
				oA.appendChild(oButton);
			}
		}
	}
	
	return false;
}

function _print(e) {
	cancelEvent(getEvent(e));

	window.print();
}

function _createNode(nodeName) {
	var oNode;
	if(nodeName) {
		if(document.createElementNS) {
			oNode = document.createElementNS("http://www.w3.org/1999/xhtml", nodeName);
		} else if(document.createElement) {
			oNode = document.createElement(nodeName);
		}
	}
	
	return oNode;
}

function attachEventHandler(o, e, f) {
	if(o) {
		if(o.addEventListener) {
			o.addEventListener(e, f, false);
		} else if(o.attachEvent) {
			o.attachEvent("on" + e, f);
		}
	}
}

function formatNumber(n, decimalPlaces) {
	if(n.toFixed) {
		return n.toFixed(2);
	} else {
		if(decimalPlaces == 0) {
			return Math.round(n);
		} else {
			var i = Math.pow(10, decimalPlaces);
			return Math.round(n * i) / i;
		}
	}
}


Number.prototype.decimalPlaces = function(decimalPlaces) {
	if(this.toFixed) {
		return this.toFixed(decimalPlaces);
	} else {
		if(decimalPlaces == 0) {
			return Math.round(this);
		} else {
			var i = Math.pow(10, decimalPlaces);
			var s = new String(Math.round(this * i) / i);
			for(var ii = 0; ii < decimalPlaces - (s.length - s.indexOf(".") - 1); ii++) {
				s += "0";
			}
			return s;
		}
	}
}

// String object extensions...
String.prototype.rtrim = function() {
	return this.replace(/\s*$/,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s*/,"");
}

String.prototype.trim = function() {
	return this.ltrim().rtrim();
}

String.prototype.capitaliseFirstWord = function() {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

String.prototype.capitaliseWords = function() {
	var astrAllWords = this.split(" ");
	
	for(var i = 0; i < astrAllWords.length; i++) {
		astrAllWords[i] = astrAllWords[i].toLowerCase();
		astrAllWords[i]=  astrAllWords[i].charAt(0).toUpperCase() + astrAllWords[i].substring(1);
	}
	
	return astrAllWords.join(" ");
}

String.prototype.capitaliseFirstWord = function() {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

// These two are not complete, but works fine for now
String.prototype.URLEncode = function() {
	var s = this.replace(/</g, "&lt;");
	s = s.replace(/>/g, "&gt;");
	return s;
}

String.prototype.URLDecode = function() {
	var s = this.replace(/&lt;/g, "<");
	s = s.replace(/&gt;/g, ">");
	return s;
}

function openWindow(url, title, width, height, scrollbar, focus, returnWin) {
  	var iLeft = (screen.width - width) / 2;
	var iTop = (screen.height - height) / 2;
	
	if(typeof(returnWin)=="undefined") {
		returnWin=true;
	}

	if(typeof(focus)=="undefined") {
		focus=true;
	}
	if(!scrollbar || scrollbar == "no" || scrollbar == "No" || scrollbar == "NO") {
		scrollbar = "no";
	} else {
		scrollbar = "yes";
	}

	var oWin = window.open(url, title, "toolbar=no,menubar=no,hotkeys=no,location=no,scrollbars=" + scrollbar + ",width=" + width + ",height=" + height + ",top=" + iTop + ",left=" + iLeft);
	if(oWin && (focus)) {
		oWin.focus();
	}
	if(returnWin) {
		return oWin;
	}
}

function textLimit(field, maxlen) {
	if (field.value.length > maxlen + 1)
		alert('Please limit your message to ' + maxlen + ' characters.');
	if (field.value.length > maxlen)
		field.value = field.value.substring(0, maxlen);
}

function setNodeTextValue(node, textValue) {
	try {
		node.innerHTML = textValue;
	} catch(e) {
		try {
			node.textContent = textValue;
		} catch(e) {
			node.innerHTML = textValue;
		}
	}
}

function getNodeTextValue(node) {
	try {
		return node.textContent;
	} catch(e) {
		return node.innerHTML;
	}
}

tdcUtils = {
	event : _event = {
		get:function(e) {
			if(e) {
				return e;
			} else if(window.event) {
				return window.event;
			}
		},
		
		getSource:function(e, o) {
			if(e.srcElement) {
				return e.srcElement;
			} else {
				return o;
			}
		},
		
		cancel:function(e) {
			if(e) {
				e.cancelBubble = true;
				if(e.preventDefault) {
					e.preventDefault();
				} else {
					e.returnValue = false;
				}
			}
		},
		
		attach:function(o, e, f) {
			if(o) {
				if(o.addEventListener) {
					o.addEventListener(e, f, false);
				} else if(o.attachEvent) {
					o.attachEvent("on" + e, f);
				}
			}
		}
	},
	
	node : _node = {
		create:function(nodeName, textValue) {
			var oNode;
			if(nodeName) {
				if(document.createElementNS) {
					oNode = document.createElementNS("http://www.w3.org/1999/xhtml", nodeName);
				} else if(document.createElement) {
					oNode = document.createElement(nodeName);
				}
				if(textValue) {
					utils.node.setTextValue(oNode, textValue);
				}
			}
			
			return oNode;
		},
		
		setTextValue:function(node, textValue) {
			try {
				node.innerHTML = textValue;
			} catch(e) {
				try {
					node.textContent = textValue;
				} catch(e) {
					node.innerHTML = textValue;
				}
			}
		},
		
		getHtmlValue:function(node) {
			try {
				return node.textContent ? node.textContent : node.innerHTML;
			} catch(e) {
				return node.innerHTML;
			}
		},
	
		getTextValue:function(node) {
			try {
				return node.textContent ? node.textContent : node.innerText;
			} catch(e) {
				return node.innerText;
			}
		},

		getTextValueNS:function(prefix, local, parentElem, index) {
			var result = utils.node.getNS(prefix, local, parentElem, index);
			if(result) {
				if (result.childNodes.length > 1) {
					return result.childNodes[1].nodeValue;
				} else {
					return result.firstChild.nodeValue;    		
				}
			} else {
				return "";
			}
		},
		
		getNS:function(prefix, local, parentElem, index) {
			var result = null;
			if(prefix && window.ActiveXObject) {
				result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
			} else {
				result = parentElem.getElementsByTagName(local)[index];
			}
			return result;
		}
	},

	form : _form = {
		originalValueAttribute : "originalValue",

		changedIndicator : _changedIndicator = {
			initialize : function(objForm) {
				if (objForm && objForm.length > 0) {
					var els = objForm.elements;
					if (els) {
						var numEls = els.length;
						for (var i = 0; i < numEls; i++) {
							var el = els[i];
							if (el) {
								el.setAttribute(this.originalValueAttribute, tdcUtils.form.elements.getValue(el));
							}
						}
					}
				}
			},
			
			hasChanged : function(objForm) {
				if (objForm && objForm.length > 0) {
					var els = objForm.elements;
					if (els) {
						var numEls = els.length;
						for (var i = 0; i < numEls; i++) {
							var el = els[i];
							if (el) {
								if (tdcUtils.form.elements.getValue(el) != el.getAttribute(this.originalValueAttribute)) {
									return true;
								}
							}
						}
					}
					return false;
				}
				return true;
			}
		},

		elements : _elements = {
			getValue : function(el) {
				if (el) {
					switch(el.nodeName.toLowerCase()) {
						case 'select':
							return el.options[el.selectedIndex].value;
						case 'checkbox':
							if (el.checked) {
								return el.name;
							}
							break;
						case 'radio':
							if (el.checked) {
								return el.name;
							}
							break;
						case 'fieldset':
							return '';
						default:
							return el.value;
					}
				}
				return '';
			}
		}
	},

	cookie : function(name, value, days, path, Domain) {
		CookieUtils = function(name, value, days, path, Domain) {
			this.name = name;
			this.value = value;
			this.path = path ? path : "/";
			this.days = days;
			this.Domain = Domain;

			this.calculateExpiry = function() {
				if (this.days) {
					var date = new Date()
					date.setTime(date.getTime()+(this.days*24*60*60*1000));
					return date.toGMTString();
				}
				else {
					return "";
				}
			}

			this.getExpiry = function() {
				var s = this.calculateExpiry();
				if (s.length > 0) return "expires=" + s;
				return "";
			}
			this.setDomain = function() {
				if(this.Domain) {
					var d = this.Domain;
					if (d.length > 0) return "domain=" + d;
					return "";
				}
			}
			this.set = function() {
				//alert('COOKIE DETAILS:\n\n' + this.name + "=" + escape(this.value) + ";" + this.getExpiry() + ";path=" + this.path +";" + this.setDomain() + ';');
				document.cookie = this.name + "=" + escape(this.value) + ";" + this.getExpiry() + ";path=" + this.path +";" + this.setDomain() + ';';
			}
			
			this.get = function() {
				var nameEquals = this.name + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i < ca.length; i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEquals) == 0) return c.substring(nameEquals.length, c.length);
				}
				return null;
			}
			
			this.remove = function() {
				this.days = -1;
				this.value = "";
				this.set();
			}
		}
		return new CookieUtils(name, value, days, path, Domain);
	}
}

var trk = {
	trkCookieName : 'si-trk',
	trkCookieAttribute : 'siTrk',

	record : function() {
		var el = document.getElementById(this.id);
		if (el) {
			
			var useId = (el && el.id);
			var valueToRecord = useId ? el.id : tdcUtils.node.getTextValue(el);
			var siTrk = el[trk.trkCookieAttribute];
			//alert('link tracking - cookie set\n\n'+ 'useId:' + useId + '\n valueToRecord:' + valueToRecord + '\n siTrk:' + siTrk );
			if (siTrk && siTrk.node) {
				var containerId = siTrk.node.id;
				if (containerId){
					valueToRecord = containerId + "-" + valueToRecord;
				}
			}

			(new tdcUtils.cookie(trk.trkCookieName, valueToRecord, '', 'http://www.tesco.com/', 'tesco.com')).set();
		}
	},	
	handleRecordRequest : function(event) {
		var srcA = tdcUtils.event.getSource(tdcUtils.event.get(event), this);
		if (srcA) {
			trk.record(srcA);
		}
	},	
	recordingObject : function(node) {
		RecordingObject = function(node) {
			this.node = node;
		}
		return new RecordingObject(node);
	},
	recordGroup : function(id) {
		if (id) {
			var node = document.getElementById(id);
			if (node) {
				if (node.hasChildNodes()) {
					var anchors = node.getElementsByTagName('a');
					if (anchors) {
						var numAnchors = anchors.length;
						for (var i = 0; i < numAnchors; i++) {
							var anchor = anchors[i];
							if (anchor) {
								anchor[trk.trkCookieAttribute] = new trk.recordingObject(node);
								tdcUtils.event.attach(anchor, 'click', trk.handleRecordRequest);
							}
						}
					}
				}
			}
		}
	}
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();

function addLinkTracking(){
	var oLinkTrackTest = document.getElementById('performLinkTracking');
	if (oLinkTrackTest){
		oLinkTrackTest.setAttribute('tracking','on');
		var oAnchors = document.getElementsByTagName('a');
		if (oAnchors){
			for (var i=0; i<oAnchors.length; i++){
				if (oAnchors[i].id){
					addEvent(oAnchors[i],'click',trk.record);
				}
			}
		}
	}

}
addEvent(window,'load',addLinkTracking);

/* modifica las caracteristicas de los menus hijos */
function menu_set(){
 var i,d='',h="<sty"+"le type=\"text/css\">",tA=navigator.userAgent.toLowerCase();if(window.opera){
 if(tA.indexOf("opera 5")>-1||tA.indexOf("opera 6")>-1){return;}}if(document.getElementById){
 for(i=1;i<20;i++){d+='ul ';h+="\n#menunav "+d+"{position:absolute;left:-9000px;width:11em;}";}
 document.write(h+"\n<"+"/sty"+"le>");}}menu_set();
/* modifica caracteristicas de apertura de menus */
function menu_init(){
 var i,g,tD,tA,tU,pp,lvl,tn=navigator.userAgent.toLowerCase();if(window.opera){
 if(tn.indexOf("opera 5")>-1||tn.indexOf("opera 6")>-1){return;}}else if(!document.getElementById){return;}
 menup=arguments;menuct=new Array;tD=document.getElementById('menunav');
if(tD){tA=tD.getElementsByTagName('A');
 for(i=0;i<tA.length;i++){tA[i].menucl=menuct.length;
menuct[menuct.length]=tA[i];g=tA[i].parentNode.getElementsByTagName("UL");
 tA[i].menusub=(g)?g[0]:false;ev=tA[i].getAttribute("onmouseover");
if(!ev||ev=='undefined'){tA[i].onmouseover=function(){
 menu_trig(this);};}ev=tA[i].getAttribute("onfocus");
if(!ev||ev=='undefined'){tA[i].onfocus=function(){menu_trig(this);};}
 if(tA[i].menusub){pp=tA[i].parentNode;
lvl=0;while(pp){if(pp.tagName&&pp.tagName=="UL"){lvl++;}pp=pp.parentNode;}
 tA[i].menulv=lvl;}}tD.onmouseout=menu_close;menu_open();}
}
function menu_trig(a){
 var b,t;if(document.menut){clearTimeout(document.menut);}document.menua=1;
b=(a.menusub)?'menu_show(':'menu_tg(';
 t='document.menut=setTimeout("'+b+a.menucl+')",160)';eval (t);
}
/*muestra los menus */
function menu_show(a,bp){
 var u,lv,oft,ofr,uw,uh,pp,aw,ah,adj,mR,mT,wW=0,
wH,w1,w2,w3,sct,pw,lc,pwv,xx=0,yy=0,wP=true;
 var iem=(navigator.appVersion.indexOf("MSIE 5")>-1)?true:false,dce=document.documentElement,dby=document.body;
document.menua=1;
 if(!bp){menu_tg(a);}u=menuct[a].menusub;
if(u.menuax&&u.menuax==1){return;}u.menuax=1;
lv=(menup[0]==1&&menuct[a].menulv==1)?true:false;
menuct[a].className=menuct[a].className.replace("menutrg","menuon");oft=parseInt(menup[3]);
ofr=parseInt(menup[4]);
 uw=u.offsetWidth;uh=u.offsetHeight;pp=menuct[a];aw=pp.offsetWidth;ah=pp.offsetHeight;while(pp){xx+=(pp.offsetLeft)?pp.offsetLeft:0;
 yy+=(pp.offsetTop)?pp.offsetTop:0;if(window.opera||navigator.userAgent.indexOf("Safari")>-1){
 if(menuct[a].menulv!=1&&pp.nodeName=="BODY"){yy-=(pp.offsetTop)?pp.offsetTop:0;}}pp=pp.offsetParent;}
 if(iem&&navigator.userAgent.indexOf("Mac")>-1){yy+=parseInt(dby.currentStyle.marginTop);}adj=parseInt((aw*ofr)/100);mR=(lv)?0:aw-adj;
 adj=parseInt((ah*oft)/100);mT=(lv)?0:(ah-adj)*-1;w3=dby.parentNode.scrollLeft;if(!w3){w3=dby.scrollLeft;}w3=(w3)?w3:0;
 if(dce&&dce.clientWidth){wW=dce.clientWidth+w3;}else if(dby){wW=dby.clientWidth+w3;}if(!wW){wW=0;wP=false;}wH=window.innerHeight;
 if(!wH){wH=dce.clientHeight;if(!wH||wH<=0){wH=dby.clientHeight;}}sct=dby.parentNode.scrollTop;if(!sct){sct=dby.scrollTop;if(!sct){
 sct=window.scrollY?window.scrollY:0;}}pw=xx+mR+uw;if(pw>wW&&wP){mR=uw*-1;mR+=10;if(lv){mR=(wW-xx)-uw;}}lc=xx+mR;if(lc<0){mR=xx*-1;}
 pw=yy+uh+ah+mT-sct;pwv=wH-pw;if(pwv<0){mT+=pwv;}u.style.marginLeft=mR+'px';u.style.marginTop=mT+'px';
 if(menup[2]==1){if(!iem){menu_anim(a,20);}}u.className="menushow";
}
/* oculta los menus */
function menu_hide(u){
 var i,tt,ua;u.menuax=0;u.className="menuhide";
ua=u.parentNode.firstChild;ua.className=ua.className.replace("menuon","menutrg");
}
function menu_tg(a,b){
 var i,u,tA,tU,pp;tA=menuct[a];pp=tA.parentNode;while(pp){if(pp.tagName=="UL"){break;}pp=pp.parentNode;}if(pp){
 tU=pp.getElementsByTagName("UL");for(i=tU.length-1;i>-1;i--){if(b!=1&&tA.menusub==tU[i]){continue;}else{menu_hide(tU[i]);}}}
}
function menu_close(evt){
 var pp,st,tS,m=true;evt=(evt)?evt:((event)?event:null);st=document.menua;if(st!=-1){if(evt){
 tS=(evt.relatedTarget)?evt.relatedTarget:evt.toElement;if(tS){pp=tS.parentNode;while(pp){if(pp&&pp.id&&pp.id=="menunav"){m=false;
 document.menua=1;break;}pp=pp.parentNode;}}if(m){document.menua=-1;if(document.menut){clearTimeout(document.menut);}
 document.menut=setTimeout("menu_clr()",360);}}}
}
function menu_clr(){
 var i,tU,tUU;document.menua=-1;tU=document.getElementById('menunav');if(tU){tUU=tU.getElementsByTagName("UL");if(tUU){
 for(i=tUU.length-1;i>-1;i--){menu_hide(tUU[i]);}}}
}
/* crea la animación */
function menu_anim(a,st){
 var g=menuct[a].menusub,sp=30,inc=20;st=(st>=100)?100:st;g.style.fontSize=st+"%";if(st<100){st+=inc;setTimeout("menu_anim("+a+","+st+")",sp);}
}
function menu_mark(){document.menuop=arguments;}
function menu_open(){
 var i,x,tA,op,pp,wH,tA,aU,r1,k=-1,kk=-1,mt=new Array(1,'','');if(document.menuop){mt=document.menuop;}op=mt[0];if(op<1){return;}
 tA=document.getElementById('menunav').getElementsByTagName("A");wH=window.location.href;r1=/index\.[\S]*/i;for(i=0;i<tA.length;i++){
 if(tA[i].href){aU=tA[i].href.replace(r1,'');if(op>0){if(tA[i].href==wH||aU==wH){k=i;kk=-1;break;}}if(op==2){if(tA[i].firstChild){
 if(tA[i].firstChild.nodeValue==mt[1]){kk=i;}}}if(op==3 && tA[i].href.indexOf(mt[1])>-1){kk=i;}if(op==4){for(x=1;x<mt.length;x+=2){
 if(wH.indexOf(mt[x])>-1){if(tA[i].firstChild&&tA[i].firstChild.data){if(tA[i].firstChild.data==mt[x+1]){kk=i;break;}}}}}}}k=(kk>k)?kk:k;
 if(k>-1){pp=tA[k].parentNode;while(pp){if(pp.nodeName=="LI"){pp.firstChild.className="menumark"+" "+pp.firstChild.className;}
 pp=pp.parentNode;}}if(kk>-1){document.menuad=1;}menu_adma();menu_admb();
}