if (!window.XMLHttpRequest)
{
    XMLHttpRequest = function()
    {
        try { return new ActiveXObject("MSXML3.XMLHTTP") } catch(ex) {}
        try { return new ActiveXObject("MSXML2.XMLHTTP.3.0") } catch(ex) {}
        try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(ex) {}
        try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(ex) {}
    }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function changeImages() {
	if (document.images) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}
function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function confPass(){
	if (document.RegisterMe.thePass.value == document.RegisterMe.CPass.value) {
		if(document.RegisterMe.thePass.value==""){
			alert("Please enter a password");
			return false;
		}else{
			if(document.RegisterMe.UName.value==""){
				alert("Please enter a Username");
				return false;
			}else{
				if(document.RegisterMe.theEmail.value==""){
					alert("Please enter a valid email address");
					return false;
				}else{
					return true;
				}
			}
		}
	}else{
	alert("Your password and confirmation of password are different. Please re-enter these details");
	document.RegisterMe.thePass.value = "";
	document.RegisterMe.CPass.value = "";
	return false;
	}
}

function giveWarningAndFixValue(field) {
//removes all non-numeric value and replaces
	var value = parseInt(field.value);
	if(!isNaN(value)) field.value = value;
	else field.value = "0";
	//used for NS4.7 because when changing value the cursor is placed in front of the value, instead of behind
	if(document.layers) field.select();
}

function isNumericValue(str) {
	var isValid = true;
	if(str.search(/^[0-9]+$/) == -1) {
		isValid = false;
	}
	return isValid;
}
function checkValue(field) {
	if(!isNumericValue(field.value)) {
		giveWarningAndFixValue(field);
	}
}
/*
function confirmdel()
{
	return window.confirm("If you delete this page all data in it will be lost. Are you sure you wish to continue?");
}

function confirmdelCont()
{
	return window.confirm("Are you sure you wish to delete this content?");
}*/

function CheckPrice(obj)
{
	//validate the price is a positive integer
	if (obj.value=="")
	{
		alert("You must enter a price.");
		return false;
	}
	else
	{	
	
		if (obj.value.search(/[^\d]/)>-1)
		{
		alert("The price must be whole dollars in numbers only with no other characters.");
		obj.value = '0';
		return false;
		}
		else
		{
		return true;
		}		
	}	
}
function CheckQuantity(obj)
{
	if (obj.value=="")
	{
		alert("You must enter a quantity.");
		return false;
	}
	else
	{
		if (obj.value.search(/[^\d]/)>-1)
		{
		alert("The quantity must be a positive number and contain numbers only with no other characters.");
		obj.value = '1';
		return false;
		}
		else
		{
		return true;
		}		
	}
}
function CheckDiscontinuedStockLevel(obj, stockLevel) {
	if (obj.value > stockLevel) {
		alert("There is only " + stockLevel + " units available in stock.");
		obj.value = stockLevel;
	}
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_timelinePlay(tmLnName, myID) { //v1.2
  //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
  var i,j,tmLn,props,keyFrm,sprite,numKeyFr,firstKeyFr,propNum,theObj,firstTime=false;
  if (document.MM_Time == null) MM_initTimelines(); //if *very* 1st time
  tmLn = document.MM_Time[tmLnName];
  if (myID == null) { myID = ++tmLn.ID; firstTime=true;}//if new call, incr ID
  if (myID == tmLn.ID) { //if Im newest
    setTimeout('MM_timelinePlay("'+tmLnName+'",'+myID+')',tmLn.delay);
    fNew = ++tmLn.curFrame;
    for (i=0; i<tmLn.length; i++) {
      sprite = tmLn[i];
      if (sprite.charAt(0) == 's') {
        if (sprite.obj) {
          numKeyFr = sprite.keyFrames.length; firstKeyFr = sprite.keyFrames[0];
          if (fNew >= firstKeyFr && fNew <= sprite.keyFrames[numKeyFr-1]) {//in range
            keyFrm=1;
            for (j=0; j<sprite.values.length; j++) {
              props = sprite.values[j]; 
              if (numKeyFr != props.length) {
                if (props.prop2 == null) sprite.obj[props.prop] = props[fNew-firstKeyFr];
                else        sprite.obj[props.prop2][props.prop] = props[fNew-firstKeyFr];
              } else {
                while (keyFrm<numKeyFr && fNew>=sprite.keyFrames[keyFrm]) keyFrm++;
                if (firstTime || fNew==sprite.keyFrames[keyFrm-1]) {
                  if (props.prop2 == null) sprite.obj[props.prop] = props[keyFrm-1];
                  else        sprite.obj[props.prop2][props.prop] = props[keyFrm-1];
        } } } } }
      } else if (sprite.charAt(0)=='b' && fNew == sprite.frame) eval(sprite.value);
      if (fNew > tmLn.lastFrame) tmLn.ID = 0;
  } }
}

function MM_timelineGoto(tmLnName, fNew, numGotos) { //v2.0
  //Copyright 1997, 2000 Macromedia, Inc. All rights reserved.
  var i,j,tmLn,props,keyFrm,sprite,numKeyFr,firstKeyFr,lastKeyFr,propNum,theObj;
  if (document.MM_Time == null) MM_initTimelines(); //if *very* 1st time
  tmLn = document.MM_Time[tmLnName];
  if (numGotos != null)
    if (tmLn.gotoCount == null) tmLn.gotoCount = 1;
    else if (tmLn.gotoCount++ >= numGotos) {tmLn.gotoCount=0; return}
  jmpFwd = (fNew > tmLn.curFrame);
  for (i = 0; i < tmLn.length; i++) {
    sprite = (jmpFwd)? tmLn[i] : tmLn[(tmLn.length-1)-i]; //count bkwds if jumping back
    if (sprite.charAt(0) == "s") {
      numKeyFr = sprite.keyFrames.length;
      firstKeyFr = sprite.keyFrames[0];
      lastKeyFr = sprite.keyFrames[numKeyFr - 1];
      if ((jmpFwd && fNew<firstKeyFr) || (!jmpFwd && lastKeyFr<fNew)) continue; //skip if untouchd
      for (keyFrm=1; keyFrm<numKeyFr && fNew>=sprite.keyFrames[keyFrm]; keyFrm++);
      for (j=0; j<sprite.values.length; j++) {
        props = sprite.values[j];
        if (numKeyFr == props.length) propNum = keyFrm-1 //keyframes only
        else propNum = Math.min(Math.max(0,fNew-firstKeyFr),props.length-1); //or keep in legal range
        if (sprite.obj != null) {
          if (props.prop2 == null) sprite.obj[props.prop] = props[propNum];
          else        sprite.obj[props.prop2][props.prop] = props[propNum];
      } }
    } else if (sprite.charAt(0)=='b' && fNew == sprite.frame) eval(sprite.value);
  }
  tmLn.curFrame = fNew;
  if (tmLn.ID == 0) eval('MM_timelinePlay(tmLnName)');
}

function MM_initTimelines() { //v4.0
    //MM_initTimelines() Copyright 1997 Macromedia, Inc. All rights reserved.
    var ns = navigator.appName == "Netscape";
    var ns4 = (ns && parseInt(navigator.appVersion) == 4);
    var ns5 = (ns && parseInt(navigator.appVersion) > 4);
    document.MM_Time = new Array(1);
    document.MM_Time[0] = new Array(1);
    document.MM_Time["Timeline1"] = document.MM_Time[0];
    document.MM_Time[0].MM_Name = "Timeline1";
    document.MM_Time[0].fps = 15;
    document.MM_Time[0][0] = new String("sprite");
    document.MM_Time[0][0].slot = 1;
    if (ns4)
        document.MM_Time[0][0].obj = document["Layer2"];
    else if (ns5)
        document.MM_Time[0][0].obj = document.getElementById("Layer2");
    else
        document.MM_Time[0][0].obj = document.all ? document.all["Layer2"] : null;
    document.MM_Time[0][0].keyFrames = new Array(1, 45);
    document.MM_Time[0][0].values = new Array(4);
    if (ns5)
        document.MM_Time[0][0].values[0] = new Array("625px", "614px", "604px", "593px", "583px", "572px", "562px", "551px", "541px", "530px", "520px", "509px", "498px", "488px", "477px", "467px", "456px", "446px", "435px", "425px", "414px", "404px", "393px", "382px", "372px", "361px", "351px", "340px", "330px", "319px", "309px", "298px", "288px", "277px", "266px", "256px", "245px", "235px", "224px", "214px", "203px", "193px", "182px", "172px", "161px");
    else
        document.MM_Time[0][0].values[0] = new Array(625,614,604,593,583,572,562,551,541,530,520,509,498,488,477,467,456,446,435,425,414,404,393,382,372,361,351,340,330,319,309,298,288,277,266,256,245,235,224,214,203,193,182,172,161);
    document.MM_Time[0][0].values[0].prop = "left";
    if (ns5)
        document.MM_Time[0][0].values[1] = new Array("121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px", "121px");
    else
        document.MM_Time[0][0].values[1] = new Array(121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121,121);
    document.MM_Time[0][0].values[1].prop = "top";
    if (!ns4) {
        document.MM_Time[0][0].values[0].prop2 = "style";
        document.MM_Time[0][0].values[1].prop2 = "style";
    }
    document.MM_Time[0][0].values[2] = new Array("hidden","visible");
    document.MM_Time[0][0].values[2].prop = "visibility";
    if (!ns4)
        document.MM_Time[0][0].values[2].prop2 = "style";
    document.MM_Time[0][0].values[3] = new Array("1","1");
    document.MM_Time[0][0].values[3].prop = "zIndex";
    if (!ns4)
        document.MM_Time[0][0].values[3].prop2 = "style";
    document.MM_Time[0].lastFrame = 45;
    for (i=0; i<document.MM_Time.length; i++) {
        document.MM_Time[i].ID = null;
        document.MM_Time[i].curFrame = 0;
        document.MM_Time[i].delay = 1000/document.MM_Time[i].fps;
    }
}

//-------- menu ---------
function initialiseMenu(menutype)
{
	if(menutype == 'True')
	{
		document.visibleMenu = null;
		document.checkMenuTimer = null;
		document.closeMenuTimer = null;
		var menu = document.getElementById("mainmenu");
		if (menu != null)
		{
			var objLICollection = menu.getElementsByTagName("TD");
			for(var i = 0; i < objLICollection.length; i++)
			{
				var objLI = objLICollection[i];        
				processNodes(objLI);
			}
			objLICollection = menu.getElementsByTagName("LI");
			for(var i = 0; i < objLICollection.length; i++)
			{
				var objLI = objLICollection[i];        
				processNodes(objLI);
			}
		}
	}
	else
	{
		//nothing required
	}
}

function initialiseAdminMenu(menutype)
{
	if(menutype == 'True')
	{
		document.visibleMenu = null;
		document.checkMenuTimer = null;
		document.closeMenuTimer = null;
		var menu = document.getElementById("adminmainmenu");
		if (menu != null)
		{
			var objLICollection = menu.getElementsByTagName("TD");
			for(var i = 0; i < objLICollection.length; i++)
			{
				var objLI = objLICollection[i];        
				processNodes(objLI);
			}
			objLICollection = menu.getElementsByTagName("LI");
			for(var i = 0; i < objLICollection.length; i++)
			{
				var objLI = objLICollection[i];        
				processNodes(objLI);
			}
		}
	}
	else
	{
		//nothing required
	}
}

function processNodes(objLI)
{
    objLI.onmouseover=hideSubMenu;

		    objLI.onmouseout=menuLostFocus;

    var subMenus = objLI.getElementsByTagName("UL");
    for(var j = 0; j  < subMenus.length; j++)
    {
        var child = subMenus.item(j);
	    if(child.nodeName == "UL")
	    {
		    objLI.onmouseover=showSubMenu;
		    objLI.onmouseout=menuLostFocus;
            if (objLI.nodeName != "TD")
            {
		        for(var k = 0; k < objLI.childNodes.length; k++)
		        {
		            var link = objLI.childNodes.item(k);
			        if(link.nodeName == "A")
			        {
				        link.style.backgroundImage = "url(/wmsimages/arrows.gif)";
				        link.style.backgroundRepeat = "no-repeat";
				        link.style.backgroundPosition = "140px center"; //controls postition of arrow
				        link.style.paddingRight = "12px";
			        }
    		    }
		    }
		    child.onmouseover=menuGotFocus;
	    }
    }
}

function menuGotFocus()
{
	resetCloseTimer();
}

function menuLostFocus()
{
	startCloseTimer();
}

function startCloseTimer()
{
    resetCloseTimer();
    document.closeMenuTimer = window.setInterval("hideAllMenus()", 500);
}

function resetCloseTimer()
{
    if (document.closeMenuTimer != null)
    {
        window.clearInterval(document.closeMenuTimer);
    }
}

function showSubMenu()
{
    showSubMenuCore(this);
}

function isChild(parent, child)
{
    var par = child;
    while (par != null)
    {
        if (parent == par)
        {
            return true;
        }
        par = par.parentNode;
    }
    return false;
}

function showSubMenuCore(objThis)
{
	if (objThis.nodeName == "TD")
	{
		// objThis.style.backgroundImage="url(images/rollover.gif)";
	}
    resetCloseTimer();
    if (document.visibleMenu != null)
    {
        if (document.visibleMenu.owner == objThis | isChild(objThis, document.visibleMenu.owner))
        {
            return;
        }
        else
        {
            if (!isChild(document.visibleMenu.owner, objThis))
            {
                if (objThis.nodeName == "TD")
                {
                    hideMenuCore(document.visibleMenu, true);
                }
                else
                {
                    hideMenuCore(document.visibleMenu, false);
                }
            }
        }
    }
    for(var i = 0; i  < objThis.childNodes.length; i++)
    {
        var menu = objThis.childNodes.item(i);
        if(menu.nodeName == "UL")			
        {
            var style = menu.style;
            style.display = "block";
            if (objThis.nodeName == "TD")
            {
                style.left = (getAbsoluteLeft(objThis) - 6) + "px"; //controls the x offset of the rollouts
                style.top = (getAbsoluteTop(objThis) + objThis.offsetHeight + 6) + "px";
            }
            else
            {
                style.left = objThis.offsetWidth + "px";
                style.top = (objThis.offsetTop -1) + "px";
            }
            menu.parentMenu = document.visibleMenu;
            document.visibleMenu = menu;
            document.visibleMenu.has_focus = 1;
            menu.owner = objThis;
            if (document.checkMenuTimer != null)
            {
                window.clearInterval(document.checkMenuTimer);
                document.checkMenuTimer = null;
            }
            document.checkMenuTimer = window.setInterval("checkMenu()", 3000);
            
            resetCloseTimer();
            break;            
        }		
    }	
}

function checkMenu()
{
    if (document.visibleMenu != null)
    {
        if (!(document.visibleMenu.has_focus == 1))
        {
            hideMenuCore(document.visibleMenu, true);
        }
    }
}

function hideAllMenus()
{
    resetCloseTimer();
    hideMenuCore(document.visibleMenu, true);
}

function hideSubMenu()
{
    hideMenuCore(document.visibleMenu, false);
}


function hideMenuCore(menu, hideAll)
{
    if (hideAll & document.checkMenuTimer != null)
    {
        window.clearInterval(document.checkMenuTimer);
        document.checkMenuTimer = null;
    }
    if (hideAll)
    {
		var p = menu;
		while (p != null)
		{
			if (p.nodeName == "TD")
			{
				// p.style.backgroundImage="url(images/button.gif)";
				break;
			}
			p = p.parentNode;
		}
        while (menu != null)
        {
            menu.style.display = "none";
            menu = getParentMenu(menu);
        }
        document.visibleMenu = null;
    }
    else
    {
        if (menu != null)
        {
			if (menu.nodeName == "TD")
			{
				// menu.style.backgroundImage="url(images/button.gif)";
			}
            menu.style.display = "none";
            document.visibleMenu = menu.parentMenu;
        }
    }
}

function getParentMenu(menu)
{
    var element = menu.parentNode;
    while (element != null)
    {
        if (element.nodeName == "TD")
        {
            return null;
        }
        if (element.nodeName == "UL")
        {
            return element;
        }
        element = element.parentNode;
    }
    return null;
}

function getAbsoluteLeft(element)
{
	if (element == null)
	{
		return 0;
	}
	var pos;
	if (element.offsetParent == null)
	{
		pos = 0;
	}
	else
	{
		pos = 0; //element.offsetParent.clientLeft;
	}
	return pos + element.offsetLeft + getAbsoluteLeft(element.offsetParent);
}

function getAbsoluteTop(element)
{
	if (element == null)
	{
		return 0;
	}
	var pos;
	if (element.offsetParent == null)
	{
		pos = 0;
	}
	else
	{
		pos = 0; //element.offsetParent.clientTop;
	}
	return pos + element.offsetTop + getAbsoluteTop(element.offsetParent);
}

function showStandard(){
	var layerToShow = document.getElementById("StandardPanel");
	var layerToHide = document.getElementById("AdvancedPanel");


    layerToShow.style.display = 'inline';
    layerToHide.style.display  = 'none';
}


function showAdvanced(){
	var layerToShow = document.getElementById("AdvancedPanel");
	var layerToHide = document.getElementById("StandardPanel");


    layerToShow.style.display = 'inline';
    layerToHide.style.display  = 'none';
}

function openNewWindow(sURL, sName, iWidth, iHeight, bResizable, bScrollbars)
{
	var iTop  = (screen.height - iHeight) / 2 ;
	var iLeft = (screen.width  - iWidth) / 2 ;
	
	var sOptions = "toolbar=no" ;
	sOptions += ",width=" + iWidth ; 
	sOptions += ",height=" + iHeight ;
	sOptions += ",resizable="  + (bResizable  ? "yes" : "no") ;
	sOptions += ",scrollbars=" + (bScrollbars ? "yes" : "no") ;
	sOptions += ",left=" + iLeft ;
	sOptions += ",top=" + iTop ;
	
	var oWindow = window.open(sURL, sName, sOptions)
	oWindow.focus();
	
	return oWindow ;
}

// --- upload images
function OpenImageUpload(ownerWindow, strImageElement, strElementName, strImageFolder, parameters)
{
	var oWindow = dialog("/components/imageuploader.aspx?ImageElement="+strImageElement+"&ElementName="+strElementName+"&ImageLocation="+strImageFolder+"&parameters="+parameters, 'UploadWindow', "width=320,height=200,resizable=0", false);
	/*var oWindow = openNewWindow("/components/imageuploader.aspx?ImageElement="+strImageElement+"&ElementName="+strElementName+"&ImageLocation="+strImageFolder+"&parameters="+parameters, 'UploadWindow', 300, 150, false, false);*/
	oWindow.mainWindow=ownerWindow;
	oWindow.opener=ownerWindow;
}
function cloneElement(elementID)
{
	var imgIndex = document.imageUploadIndex;
	var element = document.getElementById(elementID);
	if (element != null)
	{
		var elements = document.getElementsByTagName(element.nodeName);
		for (var i = 0; i < elements.length; i++)
		{
			if (elementID != null && elementID != '' && elements[i].id == elementID)
			{
				element = elements[i];
				break;
			}
		}
		
		if (element != null)
		{
			if (imgIndex == null)
			{
				imgIndex = 0;
			}
			// the element to be cloned is hidden, 0 is reserved for it
			imgIndex++;
			var clone = cloneOne(element, imgIndex);
			element.parentNode.parentNode.appendChild(clone);
			document.imageUploadIndex = imgIndex;
			return clone;
		}
	}
	return null;
}
function cloneOne(element, index)
{
	var clone = document.createElement(element.nodeName);
	var oldText = "btnDeleteImage')";
	var oldText2 = "btnDeleteImage|productImage|0')";
	var newText = "btnDeleteImage|productImage|" + index + "')";
	var newHtml = element.innerHTML.replace(oldText, newText).replace(oldText, newText).replace(oldText2, newText).replace(oldText2, newText);
	clone.innerHTML = newHtml;
	clone.controlIndex = index;
	var oAttrColl = element.attributes;
	for (i = 0; i < oAttrColl.length; i++)
    {
        oAttr = oAttrColl.item(i);
        bSpecified = oAttr.specified;
        sName = oAttr.nodeName;
        vValue = oAttr.nodeValue;
        if (bSpecified)
        {
			clone.setAttribute(sName, vValue);
		}
    }
    clone.style.cssText = element.style.cssText;
	clone.style.display = 'block';
	
	return clone;
}
function setImage(file, imageUrl, elementID, imageElementID, parameters){
	// parameters: width|height|delete_image_button_id|index_if_multiple_controls_used
	var width = null;
	var height = null;
	var deleteBtnID = null;
	var controlIndex = null;
	var parentID = null;
	if (parameters != null)
	{
		var tmp = parameters.split("|");
		if (tmp.length > 0)
		{
			width = tmp[0];
		}
		if (tmp.length > 1)
		{
			height = tmp[1];
		}
		if (tmp.length > 2)
		{
			deleteBtnID = tmp[2];
		}
		if (tmp.length > 3)
		{
			parentID = tmp[3];
		}
		if (tmp.length > 4)
		{
			controlIndex = tmp[4];
			controlIndex = parseInt(controlIndex);
		}
	}
	
	var root;
	if (parentID == null || parentID == '' || controlIndex != null)
	{
		root = document;
	}
	else
	{
		root = document.getElementById(parentID);
	}

	var elements;
	var fields = new Array();
	var btns = new Array();
	var index = 0;
	elements = root.getElementsByTagName('input');
	for (var i = 0; i < elements.length; i++)
	{
		if (elementID != null && elementID != '' && elements[i].id == elementID)
		{
			fields[index] = elements[i];
			index++;
		}
	}
	index = 0;
	for (var i = 0; i < elements.length; i++)
	{
		if (deleteBtnID != null && deleteBtnID != '' && elements[i].id == deleteBtnID)
		{
			btns[index] = elements[i];
			index++;
		}
	}
	elements = root.getElementsByTagName('img');
	var images = new Array();
	index = 0;
	for (var i = 0; i < elements.length; i++)
	{
		if (imageElementID != null && imageElementID != '' && elements[i].id == imageElementID)
		{
			images[index] = elements[i];
			index++;
		}
	}
	
	var objelement = null;
    var objimageElement = null;
	var deleteBtn = null;
    if (controlIndex != null)
    {
		if (fields.length > controlIndex)
		{
			objelement = fields[controlIndex];
		}
		if (images.length > controlIndex)
		{
			objimageElement = images[controlIndex];
		}
		if (btns.length > controlIndex)
		{
			deleteBtn = btns[controlIndex];
		}
    }
    else
    {
		if (fields.length > 0)
		{
			objelement = fields[0];
		}
		if (images.length > 0)
		{
			objimageElement = images[0];
		}
		if (btns.length > 0)
		{
			deleteBtn = btns[0];
		}
    }
    
	if (objelement != null)
    {
		objelement.value=file;
	}
	if (objimageElement != null)
	{
		objimageElement.src=imageUrl;
	}
    if (deleteBtn != null)
	{
		deleteBtn.disabled = file == null || file == '';
	}
    /*if (objimageElement != null)
	{
		if (objimageElement.onimagechanged != null) 
		{
			objimageElement.parentNode.onimagechanged(objimageElement, true, controlIndex);
		}
	}*/
	if (parentID != null && parentID != '')
	{
		var pr = document.getElementById(parentID);
		if (pr != null && pr.onimagechanged != null)
		{
			pr.onimagechanged(pr, true, controlIndex);
		}
	}
}
function OpenImageUploadPublic(strImageSrcName, strElementName, strImagePath, strProdID)
{
	var oWindow = openNewWindow("/imageUpload.aspx?imageLocation="+strImagePath+"&ElementName="+strElementName+"&ImagePath="+strImageSrcName+"&prodID="+strProdID+"&serial=3r8g89a2d-gjmvb98jf", 'UploadWindow2', 300, 150, false, false);
}

// --------- for textarea control --------
// Keep user from entering more than maxLength characters
function doKeypress(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
     }
}
// Cancel default behavior
function doBeforePaste(control){
    maxLength = control.attributes["maxLength"].value;
     if(maxLength)
     {
          event.returnValue = false;
     }
}
// Cancel default behavior and create a new paste routine
function doPaste(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
          var oTR = control.document.selection.createRange();
          var iInsertLength = maxLength - value.length + oTR.text.length;
          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
          oTR.text = sData;
     }
}
function ValidContent()
{
    if(MyReplace(document.form1.frmtitle.value, ' ', '') == '')
    {
        alert('You must provide a title for this content');
        document.form1.frmtitle.focus();
        return false;
    }
    else
    {
        showLoad();
        document.form1.action='';
        document.form1.target='';
        
        return true;
    }
}
// -------- end textarea ----------

// -------- modal window ----------
String.prototype.isArgument=function()
{
	return /^([a-zA-Z]){1,}=([0-9]){1,}$/.test(this);
}

/*
call this function just work like window.open(url,name,feature);
however, for IE5.0+, it will open a showModelessDialog window;
and For Gecko(Mozilla or Netscape), the child window will stay on top focus untill user close it.
programmed by hedger
hedger@yahoo-inc.com
*/

function dialog(url,name,feature,isModal)
{
 if(url==null){return false;}
 url = url
 if(name==null){name=""}
 if(feature==null){feature=""};
 if(window.showModelessDialog)
 {
  	var WindowFeature = new Object();
	WindowFeature["width"] = 400;
	WindowFeature["height"]  =400;
	WindowFeature["left"]  = "";
	WindowFeature["top"]  =  "";
	WindowFeature["resizable"]  = "";

	if(feature !=null && feature!="")
	{
      feature = ( feature.toLowerCase()).split(",");
	
      for(var i=0;i< feature.length;i++)
		{
          if( feature[i].isArgument())
			{
               var featureName = feature[i].split("=")[0];
			   var featureValue = feature[i].split("=")[1];
			  
			   if(WindowFeature[featureName]!=null){WindowFeature[featureName] = featureValue; }
			}
		}
	}
 
  if(WindowFeature["resizable"]==1 || WindowFeature["resizable"]=="1" || WindowFeature["resizable"].toString().toLowerCase()=="yes"){WindowFeature["resizable"] = "resizable:1;minimize:1;maximize:1;"}
  if(WindowFeature["left"]!=""){WindowFeature["left"] ="dialogLeft:" +  WindowFeature["left"] +"px;";}
  if(WindowFeature["top"]!=""){WindowFeature["top"] ="dialogTop:" +  WindowFeature["Top"] +"px;"; }
  if(window.ModelessDialog ==null){window.ModelessDialog = new Object() ; };
  if(name!="")
  {
   if(window.ModelessDialog[name]!=null && !window.ModelessDialog[name].closed )
   {
     window.ModelessDialog[name].focus();
	 return window.ModelessDialog[name];
   }
  }
	var F = WindowFeature["left"] +WindowFeature["top"] +  "dialogWidth:"+WindowFeature["width"] +" px;dialogHeight:"+WindowFeature["height"]+"px;center:1;help:0;" + WindowFeature["resizable"] +"status:0;unadorned:0;edge: raised; ;border:thick;"
	if(isModal)
	{
		window.showModalDialog(url,self,F);
		return false;
	}
	else
	{
		window.ModelessDialog[name] = window.showModelessDialog(url,self,F);
		return window.ModelessDialog[name];
	}	
 }
 else
 {
   if(document.getBoxObjectFor)
   {
	

	 if(isModal)
	 {		 
		 var Modal = window.open(url,name,"modal=1," + feature);
		 var ModalFocus = function()
		 {
			if(!Modal.closed){Modal.focus();}
			else{Modal =null;window.removeEventListener(ModalFocus,"focus");ModalFocus = null; };					
		 }
		 window.addEventListener( "focus",ModalFocus, false ); 
		 return false;
	 }
	 else
	 {
		return window.open(url,name,"modal=1," + feature);
	 }	 
   }
   else
   { 
     return window.open(url,name,feature);
   }
   //
 }
 return null;
}
   
function modal(url,feature)
{
	dialog(url,"",feature,true);
	return false;
}
//-------- end ------------

function PopulateForm(arrElements)
{
	PopulateForm2(arrElements, true);
}

function PopulateForm2(arrElements, loadChildren)
{
	for (i=0; i<arrElements.length; i++)
	{
		//index of js arrays not always sequential
		if(arrElements[i] != null)
		{
			var elementObj = document.getElementById(arrElements[i][0]);
			if(elementObj!=null)
			{
				if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "RADIO")
				{
					elementObj.checked = elementObj.value == arrElements[i][1];
				}
				else if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "CHECKBOX")
				{
					elementObj.checked = arrElements[i][1].toUpperCase() == "TRUE";
				}
				else if (elementObj.nodeName.toUpperCase() == "INPUT" && elementObj.type.toUpperCase() == "HIDDEN")
				{
					elementObj.value=arrElements[i][1];
					var img = document.getElementById(arrElements[i][0] + '_src');
					if (img != null)
					{
						if (arrElements[i][1] == null || arrElements[i][1] == '')
						{
							img.src = '/wmsimages/no_image_supplied.jpg';
						}
						else
						{
							img.src = arrElements[i][1];
						}
					}
				}
				else
				{
					elementObj.value=arrElements[i][1];
				}
				if (loadChildren && elementObj.onchange != null)
				{
					elementObj.onchange();
					elementObj.upldateCallback = function(element)
					{
						element.upldateCallback = null;
						PopulateForm2(arrElements, false);
					}
				}
				if(arrElements[i][2]=='False')
				{
					elementObj.disabled = true;					
					elementObj.Title="Editing this field is not allowed.";
				}
			}
		}
	}
}

// ------------------
function trackChanges(parentTable, change, childTable, update)
{
	if (change != null && update != null)
	{
		var prev = change.onchange;
		change.onchange = function() 
		{
			var xmlhttp =  new XMLHttpRequest();
			xmlhttp.open('POST', '/options.aspx', true);
			xmlhttp.onreadystatechange = function()
			{
				if (xmlhttp.readyState==4 || xmlhttp.readyState=="complete")
				{
					if (xmlhttp.status == 200)
					{
						updateOptions(xmlhttp.responseXML, update);
					}
					if (change.upldateCallback != null)
					{
						change.upldateCallback(change);
					}
				}
			}
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			var data = 'table=' + childTable + '&parentTable=' + parentTable + '&parentValue=' + change.value;
			xmlhttp.send(data);
			if (prev != null)
			{
				prev();
			}
		}
	}
}

function updateOptions(xml, el)
{
	var special = null;
	if (el.options.length > 0 && (el.options[0].value == null || el.options[0].value == ""))
	{
		special = el.options[0];
	}
	el.innerHTML = "";
	while (el.options.length > 0)
	{
		el.remove(0);
	}
	if (special != null)
	{
		el.options.add(special);
	}
	var opts =  xml.getElementsByTagName("option");
	for (var j = 0; j < opts.length; j++)
	{
		var option = document.createElement("OPTION");
		el.options.add(option);
		if (opts[j].firstChild == null)
		{
			option.appendChild(document.createTextNode(opts[j].text));
			option.value = opts[j].getAttribute("value");
		}
		else
		{
			option.appendChild(document.createTextNode(opts[j].firstChild.nodeValue));
			option.value = opts[j].getAttribute("value");
		}
	}
	if (el.onchange != null)
	{
		el.onchange();
	}
}

function CheckRequiredFields(formObject)
{
    var missingFields = _CheckRequiredFields_Recurse(formObject);
    
    if (missingFields && missingFields != "")
    {
        missingFields = "The following fields are required:\r\n\r\n" + missingFields;
        
        alert(missingFields);
        
        return false;
    }
    
    return true;
}

function _CheckRequiredFields_Recurse(element)
{
    var missingFields = "";
    
    for (var i = 0; i < element.childNodes.length; i++)
    {
        var childNode = element.childNodes[i];
        
        if (childNode.tagName && childNode.getAttribute("required") && childNode.getAttribute("required").toLowerCase() == "true")
        {
            var tagName = childNode.tagName.toLowerCase();
            
            if (tagName == "input")
            {
                if (childNode.type == "text")
                {
                    if (childNode.value == "")
                        missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
                }
                else if (childNode.type == "radio")
                {
                }
                else if (childNode.type == "checkbox")
                {
                }
            }
            else if (tagName == "textarea")
            {
                if (childNode.value == "")
                    missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
            }
            else if (tagName == "select")
            {
                if (childNode.selectedIndex == -1 || childNode.options[childNode.selectedIndex].value == "")
                    missingFields += (missingFields == "" ? "" : "\r\n") + _CheckRequiredFields_FormatFieldName(childNode.name);
            }
        }
        
        var childMissingFields = _CheckRequiredFields_Recurse(childNode);
        
        if (childMissingFields && childMissingFields != "")
            missingFields += (missingFields == "" ? "" : "\r\n") + childMissingFields;
    }
    
    return missingFields;
}

function _CheckRequiredFields_FormatFieldName(fieldName)
{
    if (fieldName.match(/[0-9]+?_/))
        return fieldName.substring(fieldName.indexOf("_") + 1);
        
    return fieldName;
}




function Delegate(Instance, Method)
{
	return function()
	{
		return Method.apply(Instance, arguments);
	}
}

function SetOpacity(Object, Percentage)
{
	Object.style.filter = "alpha(opacity=" + Percentage + ")";
	Object.style.opacity = Percentage / 100;
	
	Object._Opacity = Percentage;
}

function FadeElement(element, start, stop, duration, callback)
{
	var speed = Math.round(duration / 100);
	var opacity = start;
	
	if (start < stop)
	{
		for (var i = start, timer = 0; i <= stop; i++, timer++)
		{
			setTimeout(new Delegate(element, function()
			{
				SetOpacity(this, opacity);
				
				opacity++;
			}), (timer * speed));
		}
	}
	else
	{
		for (var i = start, timer = 0; i >= stop; i--, timer++)
		{
			setTimeout(new Delegate(element, function()
			{
				SetOpacity(this, opacity);
				
				opacity--;
			}), (timer * speed));
		}
	}
	
	if (callback)
	    setTimeout(callback, duration);
}
// bubs
function updateProducts(items) {
    for (var i = 0; i < items.length; i++) {
        var sel = getElementsById("prodColour", "SELECT", items[i]);
        if (sel != null && sel.length > 0) {
            updateProduct(sel[0]);
        }
    }
}

function FindParent(parentID, child) {
    var current = child;
    while (current != null) {
        if (current.id == parentID) {
            return current;
        }
        current = current.parentNode;
    }
    return null;
}

function updateProduct(sel) {
    var item = FindParent("prodItem", sel);
    var data = sel.value.split('|');
    var el;
    var ProductUniqueCode;
    el = getElementsById("itemNo", "INPUT", item);
    for (var i = 0; i < el.length; i++) {
        el[i].value = data[0];
    }

    el = getElementsById("prodUniqueCode", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = "Code: " + data[1];
        ProductUniqueCode = data[1];
    }

    el = getElementsById("prodPrice", "DIV", item);
    for (var i = 0; i < el.length; i++) {
        //        el[i].innerHTML = "RRP: " + data[2];
        el[i].innerHTML = data[2];
    }

    el = getElementsById("divSpecialText", "DIV", item);
    if (data[5] == "") {
        el[0].style.display = "none";
    }
    else {
        el[0].style.display = "block";
        el[0].innerHTML = data[5];
       }

       el = getElementsById("DiscontinuedCount", "SPAN", item);
       for (var i = 0; i < el.length; i++) {
           if (data[6] != 0) {
               el[i].innerHTML = "only " + data[6] + " left!";
           } else {
             el[i].innerHTML = "";
           }    
    }
    el = getElementsById("specialsleft", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = data[7];
    }

    //	el = getElementsById("prodImgDiv", "DIV", item);
    el = getElementsById("prodImgTD", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        if (data[3] == null || data[3] == '') {
            el[i].style.display = "none";
        }
        else {
            el[i].style.display = "";
            var imgs = getElementsById("prodImg", "IMG", item);
            for (var j = 0; j < imgs.length; j++) {
                var start = imgs[j].src.indexOf("src=");
                var end = imgs[j].src.indexOf("&", start);
                imgs[j].src = imgs[j].src.substring(0, start + 4) + data[3] + imgs[j].src.substring(end);
            }

            var lblinks = getElementsById("prodImgLightboxLink", "A", item);
            for (var g = 0; g < lblinks.length; g++) {
                lblinks[g].attributes["href"].value = "http://www.babyshopdirect.com.au/adm/watermark.aspx?src=" + data[3] + "&bgcolor=ffffff&width=240&height=180";
                //alert(lblinks[g].outerHTML);
            }

            //			var links = getElementsById("enlargedphoto", "A", item);
            //			for (var j = 0; j < links.length; j++)
            //			{
            //				links[j].onclick = function(){
            //				window.open('/adm/thumbnailer.aspx?src=/prodimg/' + ProductUniqueCode + '.jpg&width=400&height=500&bgcolor=ffffff','Product_' + ProductUniqueCode ,'width=440,height=550,toolbars=false,resizable=yes');
            //				}
            //			}
        }
    }

    el = getElementsById("TheProductName", "SPAN", item);
    for (var i = 0; i < el.length; i++) {
        el[i].innerHTML = data[4];
    }

    el = getElementsById("TheTellAFriendLink", "A", item)
    {
        for (var j = 0; j < el.length; j++) {
            el[j].onclick = function() {
                showTellFriend(data[0], '"' + data[4] + '"'); return false;
            }
        }
    }

    el = document.getElementById("addtocart");
    el.style.display = (data[8] == "True" ? "none" : "");

    el = document.getElementById("p_message");
    el.innerHTML = data[9];
}

function getElementsById(id, nodeName, parent) {
    var ret = new Array();
    var index = 0;
    var nodes;
    if (parent == null) {
        nodes = document.getElementsByTagName(nodeName);
    }
    else {
        nodes = parent.getElementsByTagName(nodeName);
    }
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id == id) {
            ret[index] = nodes[i];
            index++;
        }
    }
    return ret;
}

function getElementsByTag(nodeName, parent) {
    var ret = new Array();
    var index = 0;
    var nodes;
    if (parent == null) {
        nodes = document.getElementsByTagName(nodeName);
    }
    else {
        nodes = parent.getElementsByTagName(nodeName);
    }
    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i].id == id) {
            ret[index] = nodes[i];
            index++;
        }
    }
    return ret;
}


function showTellFriend(link, name) {
    if (document.tellFriendEditor != null && document.tellFriendEditor.parentNode.nodeName.toUpperCase() == "BODY") {
        document.body.removeChild(document.tellFriendEditor);
        document.tellFriendEditor = null;
    }
    var html = "<table>";
    html += "<tr><td>Friend's name:</td><td align='right'><input type='text' id='recipientName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Friend's email:</td><td align='right'><input type='text' id='recipientEmail' style='width: 300px;'></td></tr>";
    html += "<tr><td>Your name:</td><td align='right'><input type='text' id='senderName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Your email:</td><td align='right'><input type='text' id='senderEmail' style='width: 300px;'></td></tr>";
    html += "<tr><td>Subject:</td><td align='right'><input type='text' id='msgSubject' style='width: 300px;'></td></tr>";
    html += "<tr><td colspan='2'>Your message<br><textarea id='msgBody' cols='60' rows='6'></textarea></td></tr>";
    html += "<input type='hidden' name='tafProductID' id='tafProductID' value='" + link + "'>";
    html += "<input type='hidden' name='tafProductName' id='tafProductName' value='" + name + "'>";
    html += "<tr><td colspan='2' align='center'><input type='button' id='btnSend' value='Send' onclick='tellFriend(this);'>&nbsp;&nbsp;&nbsp;<input type='button' id='btnCancel' value='Cancel' onclick='document.body.removeChild(document.tellFriendEditor); document.tellFriendEditor = null;'></td></tr>";
    html += "</table>";

    var el = document.createElement("div");
    el.innerHTML = html;
    el.style.cssText = "position: absolute; border: solid 2px #aaaaaa; left: 30%; top: " + (document.documentElement.scrollTop + 150) + "px; padding: 3px; background-color: #eeeeee;";
    document.body.appendChild(el);
    document.tellFriendEditor = el;
}

function showTellFriend2(link, name) {
    if (document.tellFriendEditor != null && document.tellFriendEditor.parentNode.nodeName.toUpperCase() == "BODY") {
        document.body.removeChild(document.tellFriendEditor);
        document.tellFriendEditor = null;
    }
    var html = "<table>";
    //html += "<tr><td>Friend's name:</td><td align='right'><input type='text' id='recipientName' style='width: 300px;'></td></tr>";
    html += "<tr><td>Friend's email:</td><td align='right'><input type='text' id='recipientEmail' style='width: 330px;'><br /><span style='font-size: 9px;'>NB: you can add multiple email addresses separated by a comma.</td></tr>";
    html += "<tr><td>Your name:</td><td align='right'><input type='text' id='senderName' style='width: 330px;'></td></tr>";
    html += "<tr><td>Your email:</td><td align='right'><input type='text' id='senderEmail' style='width: 330px;'></td></tr>";
    html += "<tr><td>Subject:</td><td align='right'><input type='text' id='msgSubject' style='width: 330px;'></td></tr>";
    html += "<tr><td colspan='2'>Your message<br><textarea id='msgBody' cols='60' rows='12'>Hi,\r\n\r\nI have started a gift registry at Baby Shop Direct.\r\n\r\nClick this link to check it out:\r\n\r\n" + link + "\r\n\r\nSo far the list includes:\r\n" + name.replace(/~NEWLINE~/g, "\r\n") + "</textarea></td></tr>";
    html += "<tr><td colspan='2' align='center'><input type='button' id='btnSend' value='Send' onclick='tellFriend2(this);'>&nbsp;&nbsp;&nbsp;<input type='button' id='btnCancel' value='Cancel' onclick='document.body.removeChild(document.tellFriendEditor); document.tellFriendEditor = null;'></td></tr>";
    html += "</table>";

    var el = document.createElement("div");
    el.innerHTML = html;
    el.style.cssText = "position: absolute; border: solid 2px #aaaaaa; left: 30%; top: " + (document.documentElement.scrollTop + 150) + "px; padding: 3px; background-color: #eeeeee;";
    document.body.appendChild(el);
    document.tellFriendEditor = el;
}

function tellFriend(btn) {
    var val;
    val = document.getElementById("recipientName").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's name.");
        return;
    }
    var recipientName = escape(val);

    val = document.getElementById("recipientEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's address.");
        return;
    }
    var recipientEmail = escape(val);

    val = document.getElementById("senderName").value;
    if (val == null || val == '') {
        window.alert("Please enter your name.");
        return;
    }
    var senderName = escape(val);

    val = document.getElementById("senderEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your address.");
        return;
    }
    var senderEmail = escape(val);

    val = document.getElementById("msgSubject").value;
    if (val == null || val == '') {
        window.alert("Please enter the subject.");
        return;
    }
    var msgSubject = escape(val);

    val = document.getElementById("msgBody").value;
    if (val == null || val == '') {
        window.alert("Please enter the message.");
        return;
    }
    var msgBody = escape(val);

    var tafProductID = escape(document.getElementById("tafProductID").value);
    var tafProductName = escape(document.getElementById("tafProductName").value);

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', '/tellfriend.aspx', true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 || xmlhttp.readyState == "complete") {
            if (xmlhttp.status == 200) {
                window.alert('Your message has been sent.');
                document.body.removeChild(document.tellFriendEditor);
                document.tellFriendEditor = null;
            }
            else {
                window.alert('An error occured.');
                btn.disabled = false;
            }
        }
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var data = 'recipientName=' + recipientName + '&recipientEmail=' + recipientEmail + '&senderName=' + senderName + '&senderEmail=' + senderEmail + '&msgSubject=' + msgSubject + '&msgBody=' + msgBody + '&tafProductID=' + tafProductID + '&tafProductName=' + tafProductName;
    btn.disabled = true;
    xmlhttp.send(data);
}

function tellFriend2(btn) {
    var val;
    //val = document.getElementById("recipientName").value;
    //if (val == null || val == '')
    //{
    //	window.alert("Please enter your friend's name.");
    //	return;
    //}
    //var recipientName = escape(val);

    val = document.getElementById("recipientEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your friend's address.");
        return;
    }
    var recipientEmail = escape(val);

    val = document.getElementById("senderName").value;
    if (val == null || val == '') {
        window.alert("Please enter your name.");
        return;
    }
    var senderName = escape(val);

    val = document.getElementById("senderEmail").value;
    if (val == null || val == '') {
        window.alert("Please enter your address.");
        return;
    }
    var senderEmail = escape(val);

    val = document.getElementById("msgSubject").value;
    if (val == null || val == '') {
        window.alert("Please enter the subject.");
        return;
    }
    var msgSubject = escape(val);

    val = document.getElementById("msgBody").value;
    if (val == null || val == '') {
        window.alert("Please enter the message.");
        return;
    }
    var msgBody = escape(val);

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', '/tellfriend2.aspx', true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 || xmlhttp.readyState == "complete") {
            if (xmlhttp.status == 200) {
                window.alert('Your message has been sent.');
                document.body.removeChild(document.tellFriendEditor);
                document.tellFriendEditor = null;
            }
            else {
                window.alert('An error occured.');
                btn.disabled = false;
            }
        }
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var data = 'recipientName=' + /*recipientName*/'' + '&recipientEmail=' + recipientEmail + '&senderName=' + senderName + '&senderEmail=' + senderEmail + '&msgSubject=' + msgSubject + '&msgBody=' + msgBody;
    btn.disabled = true;
    xmlhttp.send(data);
}
function initialiseAdminMenu(menutype) {
    if (menutype == 'True') {
        document.visibleMenu = null;
        document.checkMenuTimer = null;
        document.closeMenuTimer = null;
        var menu = document.getElementById("adminmainmenu");
        if (menu != null) {
            var objLICollection = menu.getElementsByTagName("TD");
            for (var i = 0; i < objLICollection.length; i++) {
                var objLI = objLICollection[i];
                processNodes(objLI);
            }
            objLICollection = menu.getElementsByTagName("LI");
            for (var i = 0; i < objLICollection.length; i++) {
                var objLI = objLICollection[i];
                processNodes(objLI);
            }
        }
    }
    else {
        //nothing required
    }
}
////////////////////////////////////////AJAX BLOCK////////////////////////////////		

// XMLHttpRequest
//     FireFox and IE 7 have native XMLHttpRequest methods.
//     This function allows IE 6 and below to "work" the same way.
if (!window.XMLHttpRequest) {
    XMLHttpRequest = function() {
        try { return new ActiveXObject("MSXML3.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("MSXML2.XMLHTTP.3.0") } catch (ex) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (ex) { }
        try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (ex) { }
    }
}


// DoAjaxRequest
//     Sends an AJAX request, and calls "Callback" if successful.
//     "Callback" function is user-defined, and must have the following prototype:
//
//     function MyCallback(responseText) { ... }
//
//     Example usage:
//
//     function MyCallback(responseText) {
//         // do something with "responseText"
//     }
//
//     DoAjaxRequest("http://www.foobar.com/page.aspx", MyCallback);
function DoAjaxRequest(Address, Callback) {
    if (Address.indexOf("?") == -1)
        Address += "?r=";
    else
        Address += "&r=";

    for (var i = 0; i < 10; i++)
        Address += new String(Math.floor(Math.random() * 10));

    var Request = new XMLHttpRequest();

    Request.onreadystatechange = new Delegate(Request, function() {
        if (this.readyState == 4 && this.status == 200)
            Callback(this.responseText);
    });

    Request.open("GET", Address, true);

    Request.send(null);
}

////////////////////////////////////////END AJAX BLOCK////////////////////////////

//new checkout validation
function CheckTerms() {
    document.getElementById('SubmitCheckout').disabled = !document.getElementById('terms').checked;
}



function Delegate(Instance, Method) {
    return function() {
        return Method.apply(Instance, arguments);
    }
}

function SetOpacity(Object, Percentage) {
    Object.style.filter = "alpha(opacity=" + Percentage + ")";
    Object.style.opacity = Percentage / 100;

    Object._Opacity = Percentage;
}

function FadeElement(element, start, stop, duration, callback) {
    var speed = Math.round(duration / 100);
    var opacity = start;

    if (start < stop) {
        for (var i = start, timer = 0; i <= stop; i++, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity++;
            }), (timer * speed));
        }
    }
    else {
        for (var i = start, timer = 0; i >= stop; i--, timer++) {
            setTimeout(new Delegate(element, function() {
                SetOpacity(this, opacity);

                opacity--;
            }), (timer * speed));
        }
    }

    if (callback)
        setTimeout(callback, duration);
      }

      //hide slideshow if FF 2.x

      if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
      	var ffversion = new Number(RegExp.$1) // capture x.x portion and store as a number
      	if (ffversion >= 3) {
      		//document.write("You're using FF 3.x or above")
      	}
      	else if (ffversion >= 2) {
      		//document.write("You're using FF 2.x")
      		document.getElementById("BannerSlideShow").style.display = "none";
      	}
      	else if (ffversion >= 1) {
      		//document.write("You're using FF 1.x")
      	}
      }
      else {
      	//document.write("n/a")
      }

//Taken from jquery-global for menu intergration
//Start
/****************************************************************************************	
	[GLOBAL JQUERY FUNCTIONS]
*****************************************************************************************/
/*
$(document).ready(function() {
	try
	{
	    // Show Sign In Form
	    $('#btn-sign-in').click(function(event){event.preventDefault();$('#sign-in').fadeIn('fast');});
    	
	    // Dropdown menu
	    $('#nav-main>li').each(function(){
		    var headOffset = $('#header').offset();
		    var dropOffset = $(this).children('div').offset();
		    if (dropOffset != null && (dropOffset.left + $(this).children('div').outerWidth()) > (headOffset.left + $('#header').outerWidth())) {
			    var difference = "-" + Math.round((dropOffset.left + $(this).children('div').outerWidth()) - (headOffset.left + $('#header').outerWidth())) + "px";
			    $(this).children('div').css('left', difference);
		    }
	    });
	    $('#nav-main>li').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});
    	
	    // Init Home Carousel
	    $('#prev, #next').css('display', 'block');
	    $('#promos li').css('margin-bottom', '0');
	    $('#promos').carousel(750, '#prev', '#next', true, 5000);
    	
	    // Products Grid
	    $('div.grid-row.products>div').hover(function(){$(this).addClass('expanded');},function(){$(this).removeClass('expanded');});
    	
	    // Products Carousel
	    $('#sku-img div').carousel(250, '#prev', '#next', false);
		    $('#sku-img div input').click(function(){
			    $('#sku-img>img').attr('src',$(this).attr('name'));
		    });
    		
	    // Products 'You may also like'
	    $("#more-products").show().click(function(){
		    $(this).prev('div').is(":hidden") ? $(this).html("<span>View less</span>") :  $(this).html("<span>View more</span>");
		    $(this).prev('div').toggle();
		    $(this).prev('div').find('div.first').hover();
	    });
    	
	    // Product Description
	    if (!$.browser.msie) {$('#more-products').prev('div').hide();}; // Hiding element as normal if not IE.
	    $('#more-info').prev('div.wysiwyg').css('height','3.5em').css('overflow','hidden');
	    $("#more-info").show().click(function(){
		    $(this).prev('div.wysiwyg').css('overflow') == 'hidden' ? $(this).html("<span>Less</span>") :  $(this).html("<span>More</span>");
		    $(this).prev('div.wysiwyg').css('overflow') == 'hidden' ? $(this).prev('div.wysiwyg').css('height','auto').css('overflow','visible') : $(this).prev('div.wysiwyg').css('height','3.5em').css('overflow','hidden');
	    });
    	
	    // Product Swatches
	    $('#sku-swatches li').hover(function() {
		    $(this).append('<div><div class="inner"><em>'+$(this).children('img').attr('alt')+'</em></div></div>');
		    $(this).children('img').clone().prependTo($(this).find('div.inner'));
		    var pos = $(this).position();
		    var left = pos.left + Math.round($(this).width()/2);
		    var left = left - Math.round($(this).children('div').width()/2)
		    $(this).children('div').css('left',left);
	    }, function() {
		    $(this).find('div').remove();
	    });
    	
	    // Refine Search Hide Submit Button
	    $('.btn-refine').hide();
    		
	    // Show Filters
	    $('#filter').css('display','block');
	    $('.my-freedom #filter dl').css('visibility','visible');
    	
	    // Enable Forms to be Submitted via ENTER key
	    var AreaSelector = "#wrapper fieldset, #sign-in, #main-content, #nav-main div div, #wrapper #sidebar div.search, #footer div.inner div";
	    var ButtonSelector = "input[type='submit'],input[type='image'],button";
	    jQuery.each($(AreaSelector), function() {
            $(this).keypress(function(e) {
                if (e.which == 13 && e.target.type != 'textarea') {
                    var arrItems = $(this).find(ButtonSelector);
                    if (arrItems.length > 0) {
                        $(this).find(ButtonSelector)[0].click();
                    } else {
                        eval($(this).find(".btn-submit")[0].href);
                    }
                    return false;
                }
            });
        });

	    // Clear text input values
	    var swap_text_boxes = [];
	    jQuery.each($("input[type='text'].autoclear,input[type='password'].autoclear"), function() {
            swap_text_boxes[$(this).attr('id')] = $(this).attr('value');
            $(this).bind('focus', function() {
                if ($(this).val() == swap_text_boxes[$(this).attr('id')]) {
                    $(this).val('');
                }
            });
            $(this).bind('blur', function() {
                if ($(this).val() == '') {
                    $(this).val(swap_text_boxes[$(this).attr('id')]);
                }
            }); 
        });
    }
    catch (ex)
    {
    }
});
$(window).load(function() { try { $('#more-products').prev('div').hide(); } catch (ex) { } });  // Element hiding for IE.

//Click events for the homepage top navigation searches
function findItByPage(btn, pageID) {
    var strURL = "/ProductSearch.aspx?SearchText=" + btn.prev().attr("value") + "&PageFilter=" + pageID;
    window.location.href = strURL
}

function findItByCategory(btn, productCategory) {
    var strURL
    window.location.href = "/ProductSearch.aspx?SearchText=" + btn.prev().attr("value") + "&Category=" + productCategory;
}


/****************************************************************************************	
	[JQUERY PLUG-INS]
***************************************************************************************** /
//jQuery Infinite Carousel - Copyright 2009 Stéphane Roucheray
jQuery.fn.carousel=function(speed,previous,next,autoscroll,duration,options){var sliderList=jQuery(this).children("ul")[0];if(sliderList){var increment=jQuery(sliderList).children().outerWidth("true"),elmnts=jQuery(sliderList).children(),numElmts=elmnts.length,sizeFirstElmnt=increment,shownInViewport=Math.round(jQuery(this).width()/sizeFirstElmnt),firstElementOnViewPort=1,isAnimating=false;if(numElmts<=shownInViewport){jQuery(previous).hide();jQuery(next).hide();jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment+increment+"px");}else{for(i=0;i<shownInViewport;i++){jQuery(sliderList).css('width',(numElmts+shownInViewport)*increment+increment+"px");if(i<numElmts){jQuery(sliderList).append(jQuery(elmnts[i]).clone());};}};jQuery(previous).click(function(event){event.preventDefault();if(!isAnimating){if(firstElementOnViewPort==1){jQuery(sliderList).css('left',"-"+numElmts*sizeFirstElmnt+"px");firstElementOnViewPort=numElmts;} else{firstElementOnViewPort--;} jQuery(sliderList).animate({left:"+="+increment,y:0,queue:false},speed,"swing",function(){isAnimating=false;});isAnimating=true;}});jQuery(next).click(function(event){event.preventDefault();if(!isAnimating){if(firstElementOnViewPort>numElmts){firstElementOnViewPort=2;jQuery(sliderList).css('left',"0px");} else{firstElementOnViewPort++;} jQuery(sliderList).animate({left:"-="+increment,y:0,queue:false},speed,"swing",function(){isAnimating=false;});isAnimating=true;}});if(autoscroll&&numElmts>shownInViewport){var intervalId=window.setInterval(function(){jQuery(next).click();},duration);jQuery(this).mouseenter(function(){window.clearInterval(intervalId);});jQuery(this).mouseleave(function(){intervalId=window.setInterval(function(){jQuery(next).click();},duration);});}}};
//End jquery-global menu intergration
*/

function animate(duration, deltaCallback, completionCallback)
{
    if (this == window)
    {
        setTimeout(new Delegate({ start: new Date().getTime(), duration: duration, deltaCallback: deltaCallback, completionCallback: completionCallback }, animate), 0);
    }
    else {
        var delta = new Date().getTime() - this.start;

        if (delta < this.duration) {
            this.deltaCallback(delta);

            setTimeout(new Delegate(this, animate), 0);
        }
        else {
            this.completionCallback();
        }
    }
}
