﻿// JScript File


    
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
//window.attachEvent("onload", correctPNG);

//    	function onlyNumsAllowed(numberType, allowNegative, allowReturn, allowSpace)
//		{
//			if (allowSpace == undefined) { allowSpace = false; }
//			
//			var iKeyCode;

//			iKeyCode = event.keyCode;

//			//
//			//  If key pressed is not 0 - 9, don't allow it through.
//			//  Unless it's a float (allow .) or negative (allow -)
//			//
//			//alert(iKeyCode);
//			//alert(allowSpace);
//			
//			if( iKeyCode == 47 || (iKeyCode != 32 && iKeyCode < 44) || iKeyCode > 57 || (!allowNegative && iKeyCode == 45) || (numberType != 'float' && iKeyCode == 46) || (iKeyCode == 13 && !allowReturn) || (iKeyCode == 32 && !allowSpace)  ) {	
//				event.keyCode = null
//			}
//		}


//altered version to support firefox.
function onlyNumsAllowed(e, numberType, allowNegative, allowReturn, allowSpace)
		{
			if (allowSpace == undefined) { allowSpace = false; }
			
			var iKeyCode;

			if (window.event) // IE
			{
			    ev = window.event;
			    iKeyCode = ev.keyCode;
			}
			else if (e.which) // Netscape/Firefox/Opera
			{
			    ev = e;
			    iKeyCode = e.which;
			}

			if (iKeyCode == 8) {
			    return true; //For fireFox delete key
			}
             

			//
			//  If key pressed is not 0 - 9, don't allow it through.
			//  Unless it's a float (allow .) or negative (allow -)
			//
			//alert(iKeyCode);
			//alert(allowSpace);
			
			if( iKeyCode == 47 || (iKeyCode != 32 && iKeyCode < 44) || iKeyCode > 57 || (!allowNegative && iKeyCode == 45) || (numberType != 'float' && iKeyCode == 46) || (iKeyCode == 13 && !allowReturn) || (iKeyCode == 32 && !allowSpace)  ) {
			    			    
			    try 
			    {			    
			        if (window.event) // IE
			        {
			            ev.keyCode = null;
			        }
			        else if (e.which) // Netscape/Firefox/Opera
			        {
			            ev.which = null;
			        }
			    }
                catch (e) {}
			    
			    
			    return false;
			}
		}

		
        function toggleVisibility (elementName) {  
//	functionality no longer required 
//            if (document.getElementById(elementName).style.display == 'none') {
//                document.getElementById(elementName).style.display='block';
//            }
//            else {
//                document.getElementById(elementName).style.display='none';
//            }			
        }
        
       	//create a new XML HTTP object
		function createHTTPRequest(handler) {
			var req = null;
			if (typeof window.ActiveXObject != 'undefined' )
			{
				// Build the Microsoft variation
				req = new ActiveXObject("Microsoft.XMLHTTP");
				req.onreadystatechange = handler;
			}
			else
			{
				// Build the standards compliant variation
				req = new XMLHttpRequest();
				req.onload = handler;
			}
			return req;
		}
		
			
		//javascript variable to do the HTTP XML Request
		var xmlhttp = createHTTPRequest(completeRequest);
		//function to call the async page load to get the data
		function ajaxAddItemToBasket(product, supplier, qty, rbWarrantyID) {		
		    
		    if (product.match('#')!=null){
		
		        //Replace # with %23 so that FF with not treat MPNS with '#' in as anchor references.
		        product = product.replace("#","%23");
            }
		    
		
			var siteRoot = document.getElementById('siteRoot').innerHTML;
							
			var locStr = new String(window.location);
			locStr = locStr.toLowerCase();

			if (locStr.indexOf('checkout.aspx') > 0) {
				alert('You cannot add items to a basket whilst you are checking out...');
			}
			else {
			
			    //check if warranty is selected
			    var tbl = document.getElementById(rbWarrantyID);			   
			    
			    var warrSPN = '';			    
			    if (tbl != null) {	
			    	 var el = tbl.getElementsByTagName("INPUT");
			         for(var i = 0; i < el.length; i++){			     
			            if (el[i].type == 'radio') {
			                if(el[i].checked) {
			                    warrSPN = el[i].value;
			                    break;
			                }
			            }			            
			        }    			    
			    }
			    	
				//create a dialogue
				Dialog.info(' ', {windowParameters: {className: "alert_lite",width:250, height:80, showEffect:Element.show, hideEffect:Element.fade}, showProgress: false});
				
				window.status = '';
				document.getElementById('trBasketUpdate').style.display = 'block';				
				document.getElementById('tdBasketUpdate').style.color = '#36639B';
				document.getElementById('tdBasketUpdate').innerHTML = '<b>Adding item</b>';
				
				var strWarranty = '';
				if (warrSPN.length > 0) {
				    strWarranty = "&wrn=" + warrSPN; 
				}
	    
				//add a random parameter to cope with cacheing issues
				xmlhttp.open("GET", siteRoot + "/catalogue/addItemToBasket.aspx?spn=" +  product + "&sid=" + supplier + "&qty=" + qty + strWarranty + "&hash=" + Math.random(), true);
				
				xmlhttp.send(null);
				
			}
		}
		
		
		
		//function almost identical to ajaxAddItemToBasket, except receiving the rebate parameters
		// too scared to amend original in case I miss somewhere that uses it.
		function ajaxAddRebateItemToBasket(product, supplier, qty, promoCode, rebateKey, agreementNo, endUser, expiryDate) {
		
		    
		    if (product.match('#')!=null){
		
		        //Replace # with %23 so that FF with not treat MPNS with '#' in as anchor references.
		        product = product.replace("#","%23");
            }
		    
		
			var siteRoot = document.getElementById('siteRoot').innerHTML;
							
			var locStr = new String(window.location);
			locStr = locStr.toLowerCase();

			if (locStr.indexOf('checkout.aspx') > 0) {
				alert('You cannot add items to a basket whilst you are checking out...');
			}
			else {	
				//create a dialogue
				Dialog.info(' ', {windowParameters: {className: "alert_lite",width:250, height:80, showEffect:Element.show, hideEffect:Element.fade}, showProgress: false});
				
				window.status = '';
				document.getElementById('trBasketUpdate').style.display = 'block';				
				document.getElementById('tdBasketUpdate').style.color = '#36639B';
				document.getElementById('tdBasketUpdate').innerHTML = '<b>Adding item</b>';
			
				//add a random parameter to cope with cacheing issues
				xmlhttp.open("GET", siteRoot + "/catalogue/addItemToBasket.aspx?spn=" + product + "&sid=" + supplier + "&qty=" + qty + "&pc=" + promoCode + "&rk=" + rebateKey + "&ran=" + agreementNo + "&reu=" + endUser + "&red=" + expiryDate + "&hash=" + Math.random(), true);
				
				xmlhttp.send(null);
			}
		}
				
		
		
		function ajaxEmptyBasket() {
			var siteRoot = document.getElementById('siteRoot').innerHTML;
	
			//add a random parameter to cope with cacheing issues
			xmlhttp.open("GET", siteRoot + "/orders/emptyBasket.aspx?hash=" + Math.random(), true);
			
			xmlhttp.send(null);		
		}

		//the event handler to respond to the data coming back
		function completeRequest() {
			var siteRoot = document.getElementById('siteRoot').innerHTML;

			//if the data is ready				and status is good
			//process the response
			if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
				try {
					//take the | delimited string and put into an array
					var res = xmlhttp.responseText.split("|")
					
					//alert(xmlhttp.responseText);
								
					//update the appropriate fields for this page
					document.getElementById('basketItemID').innerHTML = res[6];
					document.getElementById('basketItemCount').innerHTML = res[1] + '&nbsp;&nbsp;';
					document.getElementById('basketSubTotal').innerHTML =  '&nbsp;&nbsp;' + res[2];
					//document.getElementById('basketDelivery').innerHTML = res[3];
					//document.getElementById('basketTotal').innerHTML = res[4];
					
					if (res[0] == 'addItem') {
						if (res[5] == '') {		
							//Dialog.closeInfo();
							
							var msg = res[10];
							
							if (msg == '') {
								msg = res[10]; //'Item NOT added to basket'
							}
							
							Dialog.setInfoMessage(msg + '<br><br><input type="button" value="' + res[13] + '" class="basketButtonsLight" onclick="Dialog.closeInfo()">&nbsp;&nbsp;<input type="button" value="' + res[12] + '" class="basketButtonsLight" onclick="document.location.href = \'' + siteRoot + '/catalogue/default.aspx?search=' + res[7] + '\'">')
							
							window.status = '';
							window.status = res[11];
							
							//document.getElementById('tdBasketUpdate').style.backgroundColor = '#36639B';
							//document.getElementById('tdBasketUpdate').style.color = 'white';
							//document.getElementById('tdBasketUpdate').innerHTML = '<b>Basket</b>';
							document.getElementById('trBasketUpdate').style.display = 'none';
						/*	if (confirm('Item NOT added to basket - do you want to search for this item?')) {					
								document.location.href = siteRoot + '/catalogue/default.aspx?search=' + res[7];
							}*/
						}
						else {
							//notify the user that the item was added		
							var msg = '<b>' + res[10] + '</b><br/>'; //+ res[5] + ' x ' + res[8] + ' added</b>'		
								
						/*	Dialog.info(msg,
								{windowParameters: {className: "alert_lite",width:250, height:50, hideEffect:Element.fade}, showProgress: false}); */
		
							Dialog.setInfoMessage(msg)						
				
							setTimeout("Dialog.closeInfo()", 1000)
							
							//alert('Item \'' + res[5] + '\' added to basket');
							window.status = '';
							window.status = res[11]; //'Item \'' + res[5] + '\' added to basket (quantity ' + res[8] + ')'
							
							document.getElementById('tdBasketUpdate').style.backgroundColor = '#36639B';
							document.getElementById('tdBasketUpdate').style.color = 'white';
							document.getElementById('tdBasketUpdate').innerHTML = msg;
							
							
							var locStr = new String(window.location);
							//alert(locStr);
							if (locStr.indexOf('viewBasket.aspx') > 0) {
								//document.location.href = 'viewBasket.aspx';
								document.location.href = locStr;+ 'a=b#related'
							}
						}
					}
									
					
					
					//create a new HTTP XML object for the next one
					xmlhttp = createHTTPRequest(completeRequest);					
				}
				catch (e) {
					//alert(e.toString());
					xmlhttp = createHTTPRequest(completeRequest);	
				}	 
				
			}
			else {
				//do nothing
			}

		}
		
		function toggleHelpVisibility (elementName) {   
			if (document.getElementById(elementName).style.display == 'none') {
                document.getElementById(elementName).style.display = 'block';
            }
            else {
                document.getElementById(elementName).style.display = 'none';
            }			
        }
        
        
        
        
        ///////////////  FAVOURITES ////////////////

    
var xmlHttpTest111 = CreateHTTPRequestTEST();

function changeField(product, supplier, action, ctlID)
{
 	 
 	var siteRoot = document.getElementById('siteRoot').innerHTML;
							
	var locStr = new String(window.location);
	locStr = locStr.toLowerCase();
			
	//create a dialogue
	Dialog.info(' ', {windowParameters: {className: "alert_lite",width:350, height:80, showEffect:Element.show, hideEffect:Element.fade}, showProgress: false});
	window.status = '';
	xmlHttpTest111.open("GET", siteRoot + "/catalogue/addItemToFavourites.aspx?spn=" + product + "&sid=" + supplier + "&action=" + action + "&lnk=" + ctlID + "&hash="+ Math.random()*100, true);
	xmlHttpTest111.onreadystatechange=stateChanged;
	xmlHttpTest111.send(null);
} 

function stateChanged() 
{ 
 
//	if (xmlHttpTest111.readyState==4)
//	{ 
//		//document.getElementById(field).value=xmlHttpTest111.responseText;
//		var res = xmlHttpTest111.responseText.split("|")	
//	}

			var siteRoot = document.getElementById('siteRoot').innerHTML;

			if ((xmlHttpTest111.readyState == 4) && (xmlHttpTest111.status == 200)) {
				try {
					//take the | delimited string and put into an array
					var res = xmlHttpTest111.responseText.split("|")
					
	//				alert(xmlhttpFV.responseText);
					document.getElementById(res[6]).innerHTML = res[5];	
					
					var nextAction;
					if (res[3] == "add") {
					    nextAction = "remove";					    
					}
					else {
					    nextAction = "add";	
					}
					
//					document.getElementById(res[6]).attributes("onclick").value = "ajaxAddItemToFavourites('" + res[1] + "', " + res[2] + ", '" + nextAction + "', '" + res[6] + "'); return false;"
//					document.getElementById(res[6]).attributes("href").value = "javascript:__doPostBack('ctl00$content1$dlProducts$ctl08$linkFavourites','')"
					
				    Dialog.setInfoMessage(res[4])
					setTimeout("Dialog.closeInfo()", 1000)					
							
					window.status = '';
//					window.status = res;
//					//window.status = res[3];
//					
//					
					//create a new HTTP XML object for the next one
					xmlHttpTest111 = CreateHTTPRequestTEST();					
				}
				catch (e) {
					//alert(e.toString());
					xmlHttpTest111 = CreateHTTPRequestTEST();	
				}	 
				
			}
			else {
				//do nothing
			}


}

function CreateHTTPRequestTEST() {
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttpTest111=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
	    {
	    xmlHttpTest111=new ActiveXObject("Msxml2.XMLHTTP");
	    }
	  catch (e)
	    {
	    xmlHttpTest111=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	  }
	return xmlHttpTest111;
}
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        //javascript variable to do the HTTP XML Request
		var xmlhttpFV = createHTTPRequest(completeRequestFV);
		//function to call the async page load to get the data
		function ajaxAddItemToFavourites(product, supplier, action, ctlID) {
//		alert(ctlID)
		
//		alert (product);
//		alert (supplier);
//		alert(action);
				
			var siteRoot = document.getElementById('siteRoot').innerHTML;
							
			var locStr = new String(window.location);
			locStr = locStr.toLowerCase();
			
				//create a dialogue
				Dialog.info(' ', {windowParameters: {className: "alert_lite",width:350, height:80, showEffect:Element.show, hideEffect:Element.fade}, showProgress: false});
				
				window.status = '';
//				document.getElementById('trBasketUpdate').style.display = 'block';				
//				document.getElementById('tdBasketUpdate').style.color = '#36639B';
//				document.getElementById('tdBasketUpdate').innerHTML = '<b>Adding item</b>';
			
				//add a random parameter to cope with cacheing issues
				//xmlhttp.open("GET", siteRoot + "/catalogue/addItemToBasket.aspx?spn=" +  product + "&sid=" + supplier + "&qty=" + qty + "&hash=" + Math.random(), true);
				xmlhttpFV.open("GET", siteRoot + "/catalogue/addItemToFavourites.aspx?spn=" + product + "&sid=" + supplier + "&action=" + action + "&lnk=" + ctlID + "&hash="+ Math.random()*100, true);
				xmlhttpFV.send(null);		
		}
        
        
        
        //the event handler to respond to the data coming back
		function completeRequestFV() {
			var siteRoot = document.getElementById('siteRoot').innerHTML;

			//if the data is ready				and status is good
			//process the response
			if ((xmlhttpFV.readyState == 4) && (xmlhttpFV.status == 200)) {
				try {
					//take the | delimited string and put into an array
					var res = xmlhttpFV.responseText.split("|")
					
	//				alert(xmlhttpFV.responseText);
					document.getElementById(res[6]).innerHTML = res[5];	
					
					var nextAction;
					if (res[3] == "add") {
					    nextAction = "remove";					    
					}
					else {
					    nextAction = "add";	
					}
					
					//document.getElementById(res[6]).attributes("onclick").value = "ajaxAddItemToFavourites('" + res[1] + "', " + res[2] + ", '" + nextAction + "', '" + res[6] + "'); return false;"
					//<A id=ctl00_content1_dlProducts_ctl07_linkFavourites style="FONT-SIZE: 1.2em" onclick="ajaxAddItemToFavourites('377794', 11, 'add', 'ctl00_content1_dlProducts_ctl07_linkFavourites'); return false;" href="javascript:__doPostBack('ctl00$content1$dlProducts$ctl07$linkFavourites','')">Ajouter aux favoris</A>
					Dialog.setInfoMessage(res[1] + ' - '+ res[4])
					setTimeout("Dialog.closeInfo()", 1000)
					
							
					window.status = '';
					//window.status = res;
					window.status = res[3];
					
					
					//create a new HTTP XML object for the next one
					xmlhttpFV = createHTTPRequest(completeRequestFV);					
				}
				catch (e) {
					//alert(e.toString());
					xmlhttpFV = createHTTPRequest(completeRequestFV);	
				}	 
				
			}
			else {
				//do nothing
			}

		}
        
        ////////////   END OF FAVOURITES  /////////////
        
        
        
        
        
        
        
        
          ////////////// PO check //////////////
    //javascript variable to do the HTTP XML Request
		var xmlhttpPO = createHTTPRequest(completeRequestPO);
		
		//function to call the async page load to get the data
		function ajaxCheckPO(key1, poTextbox, supplierID, lblField, lblCheckedField) {

			var siteRoot = document.getElementById('siteRoot').innerHTML;						
			var checkedPO = document.getElementById(lblCheckedField).innerHTML;
			var poTextboxCtl = document.getElementById(poTextbox);
			var thePO;
			
			
			if (poTextboxCtl){
			   thePO = document.getElementById(poTextbox).value;
			
			
			thePO = thePO.toUpperCase();
			checkedPO = checkedPO.toUpperCase();
			
			if (thePO != '' && thePO != checkedPO) {			
				//add a random parameter to cope with cacheing issues
				xmlhttpPO.open("GET", siteRoot + "/orders/checkPO.aspx?key1=" + key1 + "&supplier=" + supplierID + "&po=" + thePO + "&lbl=" + lblField + "&checkedValueField=" + lblCheckedField + "&hash=" + Math.random(), true);
				
				xmlhttpPO.send(null);
			}
		}
    }
		//the event handler to respond to the data coming back
		function completeRequestPO() {
			var siteRoot = document.getElementById('siteRoot').innerHTML;

			//if the data is ready				and status is good
			//process the response
			if ((xmlhttpPO.readyState == 4) && (xmlhttpPO.status == 200)) {
				try {
					//take the | delimited string and put into an array
					var res = xmlhttpPO.responseText.split("|")
					
					//alert(xmlhttpPO.responseText);
								
					//update the appropriate fields for this page
					
					//set the checked value field to the PO value which has just been checked
					document.getElementById(res[1]).innerHTML = res[2];
					
					//set the warning field to the error string
					document.getElementById(res[0]).innerHTML = res[3];
					
					
					//create a new HTTP XML object for the next one
					xmlhttpPO = createHTTPRequest(completeRequestPO);					
				}
				catch (e) {
					//alert(e.toString());
					xmlhttpPO = createHTTPRequest(completeRequestPO);	
				}	 
				
			}
			else {
				//do nothing
			}

}




/***************
   "search"
  select Element Type-Ahead for IE/Windows by Danny Goodman (www.dannyg.com)
  A bonus recipe for readers of O'Reilly's
    "JavaScript & DHTML Cookbook"
  This recipe first published at O'Reilly Network (www.oreillynet.com)
  For full implementation notes, read the article.
****************/
   
// global storage object for type-ahead info, including reset() method
var typeAheadInfo = {last:0, 
                     accumString:"", 
                     delay:500,
                     timeout:null, 
                     reset:function() {this.last=0; this.accumString=""}
                    };
// function invoked by select element's onkeydown event handler
function typeAhead() {
    
   // limit processing to IE event model supporter; don't trap Ctrl+keys
   if (window.event && !window.event.ctrlKey) {
      // timer for current event
      var now = new Date();
      // process for an empty accumString or an event within [delay] ms of last
      if (typeAheadInfo.accumString == "" || now - typeAheadInfo.last < typeAheadInfo.delay) {
         // make shortcut event object reference
         var evt = window.event;

         // get reference to the select element
         var selectElem = evt.srcElement;
         // get typed character ASCII value
         var charCode = evt.keyCode;

		 if (charCode == 9)  { return true; }
		 if (charCode == 10) { return true; }
		 if (charCode == 13) { return true; }

         // get the actual character, converted to uppercase
         var newChar =  String.fromCharCode(charCode).toUpperCase();
         // append new character to accumString storage
         typeAheadInfo.accumString += newChar;
         // grab all select element option objects as an array
         var selectOptions = selectElem.options;
         // prepare local variables for use inside loop
         var txt, nearest;
         // look through all options for a match starting with accumString
         for (var i = 0; i < selectOptions.length; i++) {
            // convert each item's text to uppercase to facilitate comparison
            // (use value property if you want match to be for hidden option value)
            txt = selectOptions[i].text.toUpperCase();
            // record nearest lowest index, if applicable
            nearest = (typeAheadInfo.accumString > txt.substr(0, typeAheadInfo.accumString.length)) ? i : nearest;
            // process if accumString is at start of option text
            if (txt.indexOf(typeAheadInfo.accumString) == 0) {
               // stop any previous timeout timer
               clearTimeout(typeAheadInfo.timeout);
               // store current event's time in object 
               typeAheadInfo.last = now;
               // reset typeAhead properties in [delay] ms unless cleared beforehand
               typeAheadInfo.timeout = setTimeout("typeAheadInfo.reset()", typeAheadInfo.delay);
               // visibly select the matching item
               selectElem.selectedIndex = i;
               // prevent default event actions and propagation
               evt.cancelBubble = true;
               evt.returnValue = false;
               // exit function
               return false;   
            }            
         }
         // if a next lowest match exists, select it
         if (nearest != null) {
            selectElem.selectedIndex = nearest;
         }
      } else {
         // not a desired event, so clear timeout
         clearTimeout(typeAheadInfo.timeout);
      }
      // reset global object
      typeAheadInfo.reset();
   }
   return true;
}


	function SubmitAndDisableButton() {
       // document.forms[0].submit();
        window.setTimeout("disableButton('" + 
           window.event.srcElement.id + "')", 0);
    }

    function disableButton(buttonID) {
        document.getElementById(buttonID).disabled=true;
    }
    
    
	function openWindow(url, name, top, width, height) {
		winContent = window.open(url, name, 'right=0, top=' + top + ',width=' + width + ',height=' + height + ', toolbar=no,scrollbars=yes,status=no, resizable=yes');
		//winContent.location = url;	
		winContent.focus();		    
	}
	
	
	 function mfs_toggle(controlID, toggleStatus, associatedID) {	 
		if (document.getElementById('mfs_tr2_' + controlID).style.display == 'none' || toggleStatus == 1) {
			document.getElementById('mfs_tr2_' + controlID).style.display='';
			document.getElementById('mfs_tr3_' + controlID).style.display='';
			document.getElementById('mfs_img_expand_' + controlID).style.display='none';
			document.getElementById('mfs_img_collapse_' + controlID).style.display='inline';

			if (associatedID != '') {
				 document.getElementById('mfs_outer_' + associatedID).style.display='none';
			}

		}
		else {
			document.getElementById('mfs_tr2_' + controlID).style.display='none';
			document.getElementById('mfs_tr3_' + controlID).style.display='none';
			document.getElementById('mfs_img_expand_' + controlID).style.display='inline';
			document.getElementById('mfs_img_collapse_' + controlID).style.display='none';

			if (associatedID != ''){
				 document.getElementById('mfs_outer_' + associatedID).style.display='block';
			}

		}
	}
	
	function capLock(e, divName){
		 kc = e.keyCode?e.keyCode:e.which;
		 sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false);
		 if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk))
		  document.getElementById(divName).style.visibility = 'visible';
		 else
		  document.getElementById(divName).style.visibility = 'hidden';
}



//Window Size Functions ------------------------------------------------------------


function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} 

function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;} 

function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;} 

function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;} 

function posRight() {return posLeft()+pageWidth();}

function posBottom() {return posTop()+pageHeight();}
           
//Dundas Charting Functions..

 
 var FADINGTOOLTIP = document.getElementById('FADINGTOOLTIP');
 var wnd_height, wnd_width;
 var tooltip_height, tooltip_width;
 var tooltip_shown=false;
 var    transparency = 100;
 var timer_id = 1;
  
 // override events
 window.onload = WindowLoading;
 window.onresize = UpdateWindowSize;
 document.onmousemove = AdjustToolTipPosition;

 function DisplayTooltip(tooltip_text)
       {
              
       
                    FADINGTOOLTIP.innerHTML = tooltip_text;
                    tooltip_shown = (tooltip_text != "")? true : false;
                    if(tooltip_text != "")
                    {
                        // Get tooltip window height
                        tooltip_height=(FADINGTOOLTIP.style.pixelHeight)? FADINGTOOLTIP.style.pixelHeight : FADINGTOOLTIP.offsetHeight;
                        transparency=0;
                        ToolTipFading();
                    } 
                    else 
                    {
                        clearTimeout(timer_id);
                        FADINGTOOLTIP.style.visibility="hidden";
                    }
                }

function AdjustToolTipPosition(e)
                {
                    if(tooltip_shown)
                    {
                        offset_y = (event.clientY + tooltip_height - document.body.scrollTop + 30 >= wnd_height) ? - 15 - tooltip_height: 20;
                        FADINGTOOLTIP.style.visibility = "visible";
                        FADINGTOOLTIP.style.left = Math.min(wnd_width - tooltip_width - 10 , Math.max(3, event.clientX + 6)) + document.body.scrollLeft + 'px';
                        FADINGTOOLTIP.style.top = event.clientY + offset_y + document.body.scrollTop + 'px';
                    }
                }

function WindowLoading()
                {
                    FADINGTOOLTIP=document.getElementById('FADINGTOOLTIP');
                    
                    if (FADINGTOOLTIP == null) {return}
        
                    // Get tooltip  window width                
                    tooltip_width = (FADINGTOOLTIP.style.pixelWidth) ? FADINGTOOLTIP.style.pixelWidth : FADINGTOOLTIP.offsetWidth;
                    
                    // Get tooltip window height
                    tooltip_height=(FADINGTOOLTIP.style.pixelHeight)? FADINGTOOLTIP.style.pixelHeight : FADINGTOOLTIP.offsetHeight;

                    UpdateWindowSize();
                }
                
function ToolTipFading()
                {
                    if(transparency <= 100)
                    {
                        FADINGTOOLTIP.style.filter="alpha(opacity="+transparency+")";
                        transparency += 5;
                        timer_id = setTimeout('ToolTipFading()', 35);
                    }
                }

function UpdateWindowSize() 
                {
                    wnd_height=document.body.clientHeight;
                    wnd_width=document.body.clientWidth;
                }

   
   		//////// Favourites ////////
		
		//javascript variable to do the HTTP XML Request
		var xmlhttpFavourites = createHTTPRequest(completeRequestFavourites);
		
		//function to call the async page load to get the data
		function ajaxItemToFavourites(product, supplier, action, linkName) {
				
			var siteRoot = document.getElementById('siteRoot').innerHTML;
	
			//create a dialogue
			Dialog.info(' ', {windowParameters: {className: "alert_lite",width:250, height:80, showEffect:Element.show, hideEffect:Element.fade}, showProgress: false});
			
			window.status = '';
			//document.getElementById('trBasketUpdate').style.display = 'block';
			//document.getElementById('tdBasketUpdate').style.color = '#36639B';
			//document.getElementById('tdBasketUpdate').innerHTML = '<b>Adding item</b>';
			
			//add a random parameter to cope with cacheing issues
			xmlhttpFavourites.open("GET", siteRoot + "/catalogue/addItemToFavourites.aspx?spn=" + product + "&sid=" + supplier + "&action=" + action + "&linkName=" + linkName + "&hash="+ Math.random()*100, true);
	 
			xmlhttpFavourites.send(null);		
		}
		
		//the event handler to respond to the data coming back
		function completeRequestFavourites() {
			var siteRoot = document.getElementById('siteRoot').innerHTML;

			//if the data is ready				and status is good
			//process the response
			if ((xmlhttpFavourites.readyState == 4) && (xmlhttpFavourites.status == 200)) {
				try {
					//take the | delimited string and put into an array
					var res = xmlhttpFavourites.responseText.split('|')
					
					//alert(xmlhttpFavourites.responseText);
					
					Dialog.setInfoMessage(res[3])	
				
					setTimeout("Dialog.closeInfo()", 1000)
					
					if (res[0] == '1' && res[2] != '') {								
						//update the appropriate fields for this page
						document.getElementById(res[2]).innerHTML = res[4];						
					}					
							
					window.status = '';
					window.status = res;								
					
					
					//create a new HTTP XML object for the next one
					xmlhttpFavourites = createHTTPRequest(completeRequestFavourites);					
				}
				catch (e) {
					//alert(e.toString());
					xmlhttpFavourites = createHTTPRequest(completeRequestFavourites);	
				}	 
				
			}
			else {
				//do nothing
			}

		}
		
		function confirmDelete(text)
    {
        var agree=confirm(text);
		if (agree)
				return true ;
		else
			return false ;
}



//AJAX functions

function schAjaxGetData(action, url) {    
    var xmlhttpMissingPrices = createHTTPRequest(
    //the event handler to respond to the data coming back
                function completeRequestMissingPrices() {

                    //if the data is ready				and status is good
                    //process the response

                    if ((xmlhttpMissingPrices.readyState == 4) && (xmlhttpMissingPrices.status == 200)) {
                        try {
                            //alert(xmlhttpMissingPrices.responseText);
                            //take the | delimited string and put into an array
                            var res = xmlhttpMissingPrices.responseText.split("^^")

                            if (res[0] == 'pricing') {
                                updatePrice(res);
                            }
                            if (res[0] == 'breadcrumbs') {
                                updateBreadCrumbs(res);
                            }
                            if (res[0] == 'deliveryRates') {
                                lookupDeliveryCallback(res[1], '');
                            }
                        }
                        catch (e) {
                            //alert(e.toString());
                        }
                    }
                    else {
                        //do nothing
                    }

                });

    xmlhttpMissingPrices.open(action, url, true);

    xmlhttpMissingPrices.send(null);
}

function getMouseXY(e) {

    if (!e)
        var e = window.event;

    // grab the x-y pos.s if browser is IE
    if (IE) {
        tempX = event.clientX + document.documentElement.scrollLeft;
        tempY = event.clientY + document.documentElement.scrollTop;

        // window.status = 'IE: X' + tempX + ', Y' + tempY ;
    }
    // grab the x-y pos.s if browser is NS
    else {
        tempX = e.pageX + _scrollLeft; //e.pageXOffset;
        tempY = e.pageY + _scrollTop; //e.pageYOffset;

        //window.status = 'NS: X' + tempX + ', Y' + tempY ;
    }

    if (tempX < 0) { tempX = 0; }
    if (tempY < 0) { tempY = 0; }

    // window.status = 'X' + tempX + ', Y' + tempY ;

    return true;
}



//Fades an element in or out..
function fade(eid) {
    var element = document.getElementById(eid);
    if (element == null)
        return;

    if (element.FadeState == null) {
        if (element.style.opacity == null
            || element.style.opacity == ''
            || element.style.opacity == '1') {
            element.FadeState = 2;
        }
        else {
            element.FadeState = -2;
        }
    }

    if (element.FadeState == 1 || element.FadeState == -1) {
        element.FadeState = element.FadeState == 1 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
    }
    else {
        element.FadeState = element.FadeState == 2 ? -1 : 1;
        element.FadeTimeLeft = TimeToFade;
        setTimeout("animateFade(" + new Date().getTime()
            + ",'" + eid + "')", 33);
    }
}

function animateFade(lastTick, eid) {

    var curTick = new Date().getTime();
    var elapsedTicks = curTick - lastTick;
    var element = document.getElementById(eid);

    if (element.FadeTimeLeft <= elapsedTicks) {

        element.style.opacity = element.FadeState == 1 ? '1' : '0';
        element.style.filter = 'alpha(opacity = '
            + (element.FadeState == 1 ? '100' : '0') + ')';

        if (element.FadeState == 1) {
            element.style.display = 'block';
        }
        else {
            element.style.display = 'none';
        }
        element.FadeState = element.FadeState == 1 ? 2 : -2;
        return;
    }

    element.FadeTimeLeft -= elapsedTicks;
    var newOpVal = element.FadeTimeLeft / TimeToFade;
    if (element.FadeState == 1)
        newOpVal = 1 - newOpVal;

    element.style.opacity = newOpVal;
    element.style.filter =
          'alpha(opacity = ' + (newOpVal * 100) + ')';

    setTimeout("animateFade(" + curTick
          + ",'" + eid + "')", 33);
}

function findPos(obj) {
    var curleft = curtop = 0;

    if (obj.offsetParent) {

        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;

        } while (obj = obj.offsetParent);


        return [curleft, curtop];
    }
}
    
//// Searchable Attributes
function showExtendedSearch(spanID, selectID) {
    var theSpan = document.getElementById(spanID);
    var theSelect = document.getElementById(selectID);

    theSpan.style.display = 'none';
    theSelect.style.display = 'block';

    theSelect.focus();
}

function extendedSearch(selectID) {
    var theSelect = document.getElementById(selectID);
    var theIndex = theSelect.selectedIndex

    document.location = theSelect.options[theIndex].value
}

//this should have the popup in for the display of the pending orders...
function displayExtendedAttributesCallback(arg, context) {

    if (arg == '') {
        return false;
    }

    var res = arg.split("¦");

    var pLeft = 250;
    var pTop = 200;

    if (res[0] != '') {
        var sourcePanel = document.getElementById(res[0]);

        var pos = findPos(sourcePanel);

        pLeft = pos[0];
        pTop = pos[1]; // - sourcePanel.offsetTop;

        if (IE) {
            pLeft = pLeft + 2 - sourcePanel.offsetLeft
        }

        //alert('left: ' + pos[0] + ' top: ' + pos[1] + ' offsetL: ' + sourcePanel.offsetLeft); 
    }

    var add = false;

    //Look for the popup div. 		            
    var dv = document.getElementById('popupAttributes');

    //create if not found.
    if (!dv) {
        dv = document.createElement('div');
        dv.setAttribute('id', 'popupAttributes');
        add = true;
    }

    //set the inner styling of the div & position etc.
    dv.style.position = "absolute";
    dv.style.left = pLeft + 'px';
    dv.style.top = pTop + 'px';
    //dv.style.height = 170 + 'px';    
    dv.style.backgroundColor = "white";
    dv.innerHTML = res[1];

    //add it to the document if it did not exist already.
    if (add) {
        dv.FadeState = -2;
        dv.style.filter = 'alpha(opacity = 0)';
        dv.style.opacity = 0;
        document.body.appendChild(dv);
    }

    //fade popup in..  
    if (dv.FadeState != "2") {
        fade(dv.id);
    }

    if (dv.style.display == 'none') {
        dv.style.display = 'block';
    }

    //alert('tempX: ' + tempX + '; top: ' + dv.style.top + '; height: ' + dv.style.height);


    //setTimeout("fade('" + dv.id + "')",3000);
}


//// CSS Class functions
function hasClass(ele, cls) {
    return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
    if (!this.hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
    if (hasClass(ele, cls)) {
        var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
        ele.className = ele.className.replace(reg, ' ');
    }
}

function height() {
    if (document.all)
        return document.body.offsetHeight;
    else if (document.layers)
        return document.body.document.height;
}

function copyToClipboard(s) {
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData("Text", s);
    }
}


function validateCustomerField(sender, args) {

    args.IsValid = true;

    if (args.Value != '') {
        if (typeof window.ActiveXObject != 'undefined') {
            // Build the Microsoft variation
            var oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            // Build the standards compliant variation
            var oXMLHTTP = new XMLHttpRequest();
        }

        var siteRoot = document.getElementById('siteRoot').innerHTML;
        var valKey = sender.attributes.getNamedItem('validation_key').nodeValue;
        var Url = siteRoot + "/ajax/validateCustomerField.ashx?value=" + args.Value + '&key=' + valKey

        oXMLHTTP.open("GET", Url, false);

        try {
            oXMLHTTP.send(null);
            if (oXMLHTTP.responseText == '1') {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
            }
        }
        catch (e) {
            alert('XMLHTTPRequest failed');
            return '';
        }
    }
}

