//===================================================================================

function preloadImage(image_src) {
	var d = document;
	var i;
	
	if (d.images) {
		if (!d.CachedImages)
			d.CachedImages = new Array();
			
        i = d.CachedImages.length
		d.CachedImages[ i ]     = new Image;
		d.CachedImages[ i ].src = image_src;
	}
}

//===================================================================================
		
function getBrowserType() {
var browsertype = '';
	if (parseInt(navigator.appVersion) > 3) {
		if (navigator.appName=="Netscape")
			browsertype = 'netscape';
	}
	if (navigator.appName.indexOf("Microsoft") != -1) {
		browsertype = 'microsoft';
	}

	return browsertype;
}

function getBrowserVersionString() {
	return navigator.appVersion.toLowerCase();
}

//===================================================================================

function getScreenHeight() {
	return this.screen.height
}

function getScreenWidth() {
	return this.screen.width
}

function getFrameWidth() {
var winW = 630;

	switch (getBrowserType()) {
		case 'netscape':
			winW = window.innerWidth;
			break;
		case 'microsoft':
			winW = document.body.offsetWidth;
			break;
	}

	return winW;
}

function getFrameHeight() {
var winH = 460;

	switch (getBrowserType()) {
		case 'netscape':
			winH = window.innerHeight;
			break;
		case 'microsoft':
			if (document.body != null)
				winH = document.body.offsetHeight;
			else
				winH = screen.availHeight;
			
			break;
	}
		
	return winH;
}

function showscreensize() {
	alert('Screen Dimensions: ' + getScreenWidth() + ',' + getScreenHeight() );
}

//===================================================================================

function cleanstring(sourcestring) {
	var deststring = '';
	var index, stringlen;

	stringlen = sourcestring.length;
	index     = 0;
	while (index < stringlen) {
		if (sourcestring.charCodeAt(index) == 160) {
			if (deststring == '')
				deststring = ' ';
			else
				deststring += ' ';
		}
		else {
			if (deststring == '')
				deststring = sourcestring.charAt(index);
			else
				deststring += sourcestring.charAt(index);
		}
		
		index++;	
	}
	return deststring;	
}

//===================================================================================

function ajax(url, vars, callbackFunction){
 
        var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
 
        request.open("POST", url, true);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
 
        request.onreadystatechange = function(){
 
                if (request.readyState == 4 && request.status == 200) {
 
                        if (request.responseText){
 
                                callbackFunction(request.responseText);
                        }
                }
        }
        request.send(vars);
}

//===================================================================================

function getInnerText(element) {
	var textvalue;

	textvalue = '';
	switch (getbrowsertype()) {
		case 'netscape':
			textvalue = element.textContent;
			break;
		case 'microsoft':
			textvalue = element.innerText;
			break;
	}
	return textvalue;
}

//===================================================================================

function getImgString(imgSrc, imgId, imgClass, imgWidth, imgHeight, imgAlign, imgAlt) {
	var ReturnValue    = '';
	var BrowserVersion = getBrowserVersionString();

	if (getBrowserType() == 'microsoft' && (BrowserVersion.indexOf('msie 6') != -1 || BrowserVersion.indexOf('msie 5') != -1)) {
		ReturnValue = '<span';
		if (imgId != '')
			ReturnValue = ReturnValue + ' id="' + imgId + '"';
		if (imgClass != '')
			ReturnValue = ReturnValue + ' class="' + imgClass + '"';

		ReturnValue = ReturnValue + ' style="position:relative;';

		if (imgWidth != '')
			ReturnValue = ReturnValue + ' width: ' + imgWidth + 'px;';
		if (imgHeight != '')
			ReturnValue = ReturnValue + ' height: ' + imgHeight + 'px;';
 		if (imgSrc != '')
			ReturnValue = ReturnValue + ' filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + imgSrc + '\', sizingMethod=\'scale\');';
		if (imgAlign != '')
			ReturnValue = ReturnValue + ' text-align: ' + imgAlign + ';';
			
		ReturnValue = ReturnValue + ' "';
		
		if (imgAlt != '')
			ReturnValue = ReturnValue + ' alt="' + imgAlt + '"';

		ReturnValue = ReturnValue + '></span>';
	}
	else {
		ReturnValue = '<img'
		if (imgId != '')
			ReturnValue = ReturnValue + ' id="' + imgId + '"';
		if (imgSrc != '')
			ReturnValue = ReturnValue + ' src="' + imgSrc + '"';
		if (imgClass != '')
			ReturnValue = ReturnValue + ' class="' + imgClass + '"';
		ReturnValue = ReturnValue + ' style="position:relative;';
		if (imgWidth != '')
			ReturnValue = ReturnValue + ' width: ' + imgWidth + 'px;';
		if (imgHeight != '')
			ReturnValue = ReturnValue + ' height: ' + imgHeight + 'px;';
		if (imgAlign != '')
			ReturnValue = ReturnValue + ' text-align: ' + imgAlign + ';';

		ReturnValue = ReturnValue + ' "';

		if (imgAlt != '')
			ReturnValue = ReturnValue + ' alt="' + imgAlt + '"';

		ReturnValue = ReturnValue + '>';
	}

	return ReturnValue;	
}

//===================================================================================

function setImageOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

//===================================================================================

function initImage(imageId) {
	var image; 
	image = document.getElementById(imageId);
	if (image != null) {
		setImageOpacity(image, 0);
		image.style.visibility = 'visible';
		fadeinImage(imageId,0);
	}
}

function fadeinImage(objId, opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setImageOpacity(obj, opacity);
			opacity += 10;
			window.setTimeout("fadeinImage('"+objId+"',"+opacity+")", 100);
		}
	}
}

//===================================================================================

function FoldersManager() {
	this.SelectedFolders    = new Array();
	this.SelectedIdFolders  = new Array();
	this.SelectedFolderType = new Array();
	
	this.CurrentFolderDepth = 0;
	this.getFolder          = getFolderPath;
	this.addFolder          = addFolder;
	this.delFolder          = delFolder;
	this.changeFolder       = changeFolder;
	this.clearFolders       = clearFolders;
	this.getFolderLevel     = getFolderLevel;
	this.getIdFolder        = getIdFolder;
	this.getFolderType      = getFolderType;
}

function getFolderPath () {
	var FolderIndex;
	var ReturnValue = '';
	
	for (FolderIndex = 0; FolderIndex < this.CurrentFolderDepth; FolderIndex++)
		ReturnValue = ReturnValue + '&nbsp;/&nbsp;' + this.SelectedFolders[FolderIndex];
		
	return ReturnValue
}

function addFolder(FolderName, IdFolder, FolderType) {
	this.SelectedFolders[this.CurrentFolderDepth]    = FolderName;
	this.SelectedIdFolders[this.CurrentFolderDepth]  = IdFolder; 
	this.SelectedFolderType[this.CurrentFolderDepth] = FolderType;
	this.CurrentFolderDepth                        += 1;
}

function delFolder () {
	this.CurrentFolderDepth                      -= 1;
	this.SelectedFolders[this.CurrentFolderDepth]    = null;
	this.SelectedIdFolders[this.CurrentFolderDepth]  = null; 
	this.SelectedFolderType[this.CurrentFolderDepth] = null;

	this.SelectedFolders.length    = this.CurrentFolderDepth;
	this.SelectedIdFolders.length  = this.CurrentFolderDepth;
	this.SelectedFolderType.length = this.CurrentFolderDepth;

}

function changeFolder(FolderName, IdFolder, FolderType) {
	this.SelectedFolders[this.CurrentFolderDepth -1]    = FolderName;
	this.SelectedIdFolders[this.CurrentFolderDepth -1]  = IdFolder;
	this.SelectedFolderType[this.CurrentFolderDepth -1] = FolderType;
}

function clearFolders() {
	var FolderIndex;
	
	for (FolderIndex = 0; FolderIndex < this.CurrentFolderDepth; FolderIndex++) {
		this.SelectedFolders[FolderIndex]    = null;
		this.SelectedIdFolders[FolderIndex]  = null; 
		this.SelectedFolderType[FolderIndex] = null;
	}

	this.CurrentFolderDepth        = 0;
	this.SelectedFolders.length    = this.CurrentFolderDepth;
	this.SelectedIdFolders.length  = this.CurrentFolderDepth;
	this.SelectedFolderType.length = this.CurrentFolderDepth
}

function getFolderLevel() {
	return this.CurrentFolderDepth
}

function getIdFolder(FolderLevel) {
	return this.SelectedIdFolders[FolderLevel]; 
}

function getFolderType(FolderLevel) {
	return this.SelectedFolderType[FolderLevel]; 
}

//===================================================================================

function MsMenu() {
	this.MenuItems   = new Array();
	this.addMenuItem = addMenuItem;
	this.writeBanner = writeBanner;
}

function addMenuItem(Id, Text, Href, Class, OnClick) {
	var Itemindex;
	Itemindex = this.MenuItems.length;
	
	this.MenuItems[Itemindex]         = new Object();
	this.MenuItems[Itemindex].Id      = Id;
	this.MenuItems[Itemindex].Text    = Text;
	this.MenuItems[Itemindex].Href    = Href;
	this.MenuItems[Itemindex].Class   = Class;
	this.MenuItems[Itemindex].OnClick = OnClick;
}

function writeBanner(Width, Height) {

	var ImageHeight;
	var BannerImage;
	var TextFontSize;
	if (getScreenWidth() >= 2048) {
		ImageHeight   = 100;
		TextFontSize  = 380;
		BannerImage   = 'images/pattern2048.jpg';
	}
	else {
		if (getScreenWidth() >= 1920) {
			ImageHeight   = 100;
			TextFontSize  = 380;
			BannerImage   = 'images/pattern1920.jpg';
		}
		else {
			if (getScreenWidth() >= 1856) {
				ImageHeight   = 100;
				TextFontSize  = 380;
				BannerImage   = 'images/pattern1856.jpg';
			}
			else {
				if (getScreenWidth() >= 1800) {
					ImageHeight   = 100;
					TextFontSize  = 380;
					BannerImage   = 'images/pattern1800.jpg';
				}
				else {
					if (getScreenWidth() >= 1792) {
						ImageHeight   = 100;
						TextFontSize  = 380;
						BannerImage   = 'images/pattern1792.jpg';
					}
					else {
						if (getScreenWidth() >= 1680) {
							ImageHeight   = 100;
							TextFontSize  = 380;
							BannerImage   = 'images/pattern1680.jpg';
						}
						else {
							if (getScreenWidth() >= 1600) {
								ImageHeight   = 100;
								TextFontSize  = 380;
								BannerImage   = 'images/pattern1600.jpg';
							}
							else {
								if (getScreenWidth() >= 1440) {
									ImageHeight   = 100;
									TextFontSize  = 380;
									BannerImage   = 'images/pattern1400.jpg';
								}
								else {
									if (getScreenWidth() >= 1360) {
										ImageHeight   = 100;
										TextFontSize  = 380;
										BannerImage   = 'images/pattern1400.jpg';
									}
									else {
										if (getScreenWidth() >= 1280) {
											ImageHeight   = 100;
											TextFontSize  = 380;
											BannerImage   = 'images/pattern1280.jpg';
										}
										else {
											if (getScreenWidth() >= 1152) {
												ImageHeight   = 100;
												TextFontSize  = 380;
												BannerImage   = 'images/pattern1152.jpg';
											}
											else {
												if (getScreenWidth() >= 1024) {
													ImageHeight   = 100;
													TextFontSize  = 350;
													BannerImage   = 'images/pattern1024.jpg';
												}
												else {
													ImageHeight   = 78;
													TextFontSize  = 270;
													BannerImage   = 'images/pattern800.jpg';
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
	
	document.write('<table width="' + Width + '" height="' + Height + '" border="0" cellpadding="0" cellspacing="0">');
	document.write('<tr>');
	document.write('<td style=" width: ' + Width + 'px; height: ' + ImageHeight + 'px; text-align: center; background-image: url(' + BannerImage + '); background-repeat: no-repeat; background-position: center;">');
	document.write('<div style="font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: ' + TextFontSize + '%; font-weight: normal; font-stretch: normal; color: #f3f1f1; align: center; letter-spacing: 4pt;">Madison Strand</div>');
	document.write('</td>');
	document.write('</tr>');
	document.write('<Tr>');
//	document.write('<Td width="' + Width + '" height="' + (Height - ImageHeight -7) + '" align="left" bgcolor="#f3f1f1">');
	document.write('<Td class="menucell" width="' + Width + '" height="' + (Height - ImageHeight -7) + '">');
	if (this.MenuItems.length > 0) {
		var i;

		document.write('<Table id="tablemenu" Border="0" CellSpacing="0" CellPadding="0"  height="100%"><Tr>');
		for (i = 0; i < this.MenuItems.length; i++)
			document.write('<Td align="center"  Height="100%"><a Href="' + this.MenuItems[i].Href + '" id="' + this.MenuItems[i].id + '" class="' + this.MenuItems[i].Class + '" onclick="' + this.MenuItems[i].OnClick + '">' + this.MenuItems[i].Text + '</a></Td>');

		document.write('</Tr></Table>');
	}
	else
		document.write('&nbsp;');

	document.write('</Td>');
	document.write('</Tr>');
	document.write('<Tr>');
	document.write('<Td width="' + Width + '" Height="7">');
	document.write('<Img id="headershadow" Src="images/drop-shadow31.png" Border="0" Height="7" width="' + Width + '" Name="MainMenuHome25" Alt="">');
	document.write('</Td>');
	document.write('</Tr>');
	document.write('</table>');
}

//===================================================================================
function associateObjWithEvent(obj, methodName){
    return (function(e){
        e = e||window.event;
        return obj[methodName](e, this);
    });
}


function MouseOvers() {
	this.EvtMgr    = new Array();
	this.addItem   = addItem;
}

function addItem(idAnchor, idImg, ImageSrcIn, ImageSrcOut) {
    var element = document.getElementById(idAnchor);
    if(element){
		element.idImg       = idImg;
		element.ImageSrcIn  = ImageSrcIn;
		element.ImageSrcOut = ImageSrcOut;
        element.onmouseover = associateObjWithEvent(this, "doMouseOver");
        element.onmouseout  = associateObjWithEvent(this, "doMouseOut");
    }
}

MouseOvers.prototype.doMouseOver = function(event, element){
	var elImg = document.getElementById(element.idImg);
	if (elImg)
		elImg.src = element.ImageSrcIn;
}

MouseOvers.prototype.doMouseOut = function(event, element){
	var elImg = document.getElementById(element.idImg);
	if (elImg)
		elImg.src = element.ImageSrcOut;
}

//===================================================================================

function ImageScroller() {
	this.ImageList  = new Array();
	this.IdPhotos   = new Array();
	this.FileNames  = new Array();
	
	this.addImage               = addImage;
	this.getIndexUsingIdPhoto   = getIndexUsingIdPhoto;
	this.getIndexUsingPhotoName = getIndexUsingPhotoName;
	this.getImageIdPhoto        = getImageIdPhoto;
	this.getImageCaption        = getImageCaption;
	this.getImageFileName       = getImageFileName;
	this.getImageUrl            = getImageUrl;
	this.getImageCount          = getImageCount;
	this.nextImage              = nextImage;
	this.previousImage          = previousImage;
}

function addImage(IdPhoto, Caption, FileName, url) {
	var ImageIndex;

	ImageIndex                          = this.ImageList.length;
	this.ImageList[ImageIndex]          = new Object();
	this.ImageList[ImageIndex].IdPhoto  = IdPhoto;
	this.ImageList[ImageIndex].Caption  = Caption;
	this.ImageList[ImageIndex].FileName = FileName;
	this.ImageList[ImageIndex].url      = url;
	
	this.IdPhotos[IdPhoto]              = ImageIndex;
	this.FileNames[FileName]            = ImageIndex;
}

function getIndexUsingIdPhoto(IdPhoto) {
	return this.IdPhotos[IdPhoto];
}

function getIndexUsingPhotoName(PhotoName) {
	return this.FileNames[PhotoName];
}

function getImageIdPhoto(ImageIndex) {
	return this.ImageList[ImageIndex].IdPhoto;
}

function getImageCaption(ImageIndex) {
	return this.ImageList[ImageIndex].Caption;
}

function getImageFileName(ImageIndex) {
	return this.ImageList[ImageIndex].FileName;
}

function getImageUrl(ImageIndex) {
	return this.ImageList[ImageIndex].url;
}

function getImageCount() {
	return this.ImageList.length;
}

function nextImage(indexImage, idImage, idImageTitle, ImageWidth, ImageHeight) {
	var elementImg;
	var elementTxt;

/*	
	elementImg = document.getElementById(idImage);
	elementTxt = document.getElementById(idImageTitle);
	if (elementImg != null) {
		indexImage++;
		if (indexImage >= this.getImageCount())
			indexImage = 0;
			
		elementImg.src = 'images/blank.jpg';
		elementImg.src = this.getImageUrl(indexImage) + '&width=' + ImageWidth + '&height=' + ImageHeight;
		
		if (elementTxt != null) {
			elementTxt.innerHTML = this.getImageCaption(indexImage)
		}
	}
*/

	var elementParent;
	
	elementImg = document.getElementById(idImage);
	elementTxt = document.getElementById(idImageTitle);
	if (elementImg != null) {
		indexImage++;
		if (indexImage >= this.getImageCount())
			indexImage = 0;

		elementParent = elementImg.parentNode;
		elementParent.removeChild(elementImg);
		elementImg = document.createElement("img");
		elementImg.id  = idImage;
		elementImg.src = 'images/blank.jpg';
		elementImg.src = this.getImageUrl(indexImage) + '&width=' + ImageWidth + '&height=' + ImageHeight;
		elementParent.appendChild(elementImg);
		if (elementTxt != null) {
			elementTxt.innerHTML = this.getImageCaption(indexImage)
		}
		initImage(elementImg);
	}

	return indexImage;
}

function previousImage(indexImage, idImage, idImageTitle, ImageWidth, ImageHeight) {
	var elementImg;
	var elementTxt;
	var elementTxt;

/*	
	elementImg = document.getElementById(idImage);
	elementTxt = document.getElementById(idImageTitle);
	if (elementImg != null) {
		indexImage--;
		if (indexImage < 0)
			indexImage = this.getImageCount() -1;

		elementImg.src = 'images/blank.jpg';
		elementImg.src = this.getImageUrl(indexImage) + '&width=' + ImageWidth + '&height=' + ImageHeight;
		if (elementTxt != null) {
			elementTxt.innerHTML = this.getImageCaption(indexImage)
		}
	}
*/

	elementImg = document.getElementById(idImage);
	elementTxt = document.getElementById(idImageTitle);
	if (elementImg != null) {
		indexImage--;
		if (indexImage < 0)
			indexImage = this.getImageCount() -1;

		elementParent = elementImg.parentNode;
		elementParent.removeChild(elementImg);
		elementImg = document.createElement("img");
		elementImg.id  = idImage;
		elementImg.src = 'images/blank.jpg';
		elementImg.src = this.getImageUrl(indexImage) + '&width=' + ImageWidth + '&height=' + ImageHeight;
		elementParent.appendChild(elementImg);
		if (elementTxt != null) {
			elementTxt.innerHTML = this.getImageCaption(indexImage)
		}
		initImage(elementImg);
	}


	return indexImage;
}

//===================================================================================

function getRadioCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

//===================================================================================

function PriceOptions() {
	this.PriceList               = new Array();
	this.PriceListIndex          = new Array();
	this.addItemPrice            = addItemPrice;
	this.getItemIdPrice          = getItemIdPrice;
	this.getItemIndex            = getItemIndex;
	this.getItemPriceDescription = getItemDescription;
	this.getItemPriceValue       = getItemPriceValue;
	this.getItemCount            = getItemCount;
}

function addItemPrice(IdPrice, PriceDescription, PriceValue) {
	var indexPriceList;
	
	indexPriceList                 = this.PriceList.length;
	this.PriceList[indexPriceList] = new Object();
	
	if (this.PriceList[indexPriceList] != null) {
		this.PriceList[indexPriceList].IdPrice          = IdPrice;
		this.PriceList[indexPriceList].PriceDescription = PriceDescription;
		this.PriceList[indexPriceList].PriceValue       = PriceValue;

		this.PriceListIndex[IdPrice]                    = indexPriceList;
	}
}

function getItemIndex(IdPrice) {
	return this.PriceListIndex[IdPrice];
}

function getItemIdPrice(indexPriceList) {
	return this.PriceList[indexPriceList].IdPrice;
}

function getItemDescription(indexPriceList) {
	return this.PriceList[indexPriceList].PriceDescription;
}

function getItemPriceValue(indexPriceList) {
	return this.PriceList[indexPriceList].PriceValue;
}

function getItemCount() {
	return this.PriceList.length;
}

//===================================================================================

function parseMacro(TextField) {
	var ReturnValue;
	var ScreenWidth;
	
	if (getScreenWidth() >= 1152)
		ScreenWidth = 1152;
	else if (getScreenWidth() >= 1024)
		ScreenWidth = 1024;
	else
		ScreenWidth = 800;
	  
	
	ReturnValue = TextField.replace('%size%', ScreenWidth);
	
	return ReturnValue;
}

//===================================================================================

var http_request = false;

function makeRequest(url) {

    http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = alertContents;
    http_request.open('GET', url, true);
    http_request.send(null);

}

function alertContents() {

    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            alert(http_request.responseText);
        } else {
            alert('There was a problem with the request.');
        }
    }

}

//===================================================================================

function sprintf() {
    function pad(str, len, chr, leftJustify) {
	var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
	return leftJustify ? str + padding : padding + str;

    }

    function justify(value, prefix, leftJustify, minWidth, zeroPad) {
	var diff = minWidth - value.length;
	if (diff > 0) {
	    if (leftJustify || !zeroPad) {
		value = pad(value, minWidth, ' ', leftJustify);
	    } else {
		value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
	    }
	}
	return value;
    }

    function formatBaseX(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
	// Note: casts negative numbers to positive ones
	var number = value >>> 0;
	prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
	value = prefix + pad(number.toString(base), precision || 0, '0', false);
	return justify(value, prefix, leftJustify, minWidth, zeroPad);
    }

    function formatString(value, leftJustify, minWidth, precision, zeroPad) {
	if (precision != null) {
	    value = value.slice(0, precision);
	}
	return justify(value, '', leftJustify, minWidth, zeroPad);
    }

    var a = arguments, i = 0, format = a[i++];
    return format.replace(sprintf.regex, function(substring, valueIndex, flags, minWidth, _, precision, type) {
	    if (substring == '%%') return '%';

	    // parse flags
	    var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false;
	    for (var j = 0; flags && j < flags.length; j++) switch (flags.charAt(j)) {
		case ' ': positivePrefix = ' '; break;
		case '+': positivePrefix = '+'; break;
		case '-': leftJustify = true; break;
		case '0': zeroPad = true; break;
		case '#': prefixBaseX = true; break;
	    }

	    // parameters may be null, undefined, empty-string or real valued
	    // we want to ignore null, undefined and empty-string values

	    if (!minWidth) {
		minWidth = 0;
	    } else if (minWidth == '*') {
		minWidth = +a[i++];
	    } else if (minWidth.charAt(0) == '*') {
		minWidth = +a[minWidth.slice(1, -1)];
	    } else {
		minWidth = +minWidth;
	    }

	    // Note: undocumented perl feature:
	    if (minWidth < 0) {
		minWidth = -minWidth;
		leftJustify = true;
	    }

	    if (!isFinite(minWidth)) {
		throw new Error('sprintf: (minimum-)width must be finite');
	    }

	    if (!precision) {
		precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : void(0);
	    } else if (precision == '*') {
		precision = +a[i++];
	    } else if (precision.charAt(0) == '*') {
		precision = +a[precision.slice(1, -1)];
	    } else {
		precision = +precision;
	    }

	    // grab value using valueIndex if required?
	    var value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];

	    switch (type) {
		case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad);
		case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
		case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
		case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
		case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
		case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
		case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
		case 'i':
		case 'd': {
			      var number = parseInt(+value);
			      var prefix = number < 0 ? '-' : positivePrefix;
			      value = prefix + pad(String(Math.abs(number)), precision, '0', false);
			      return justify(value, prefix, leftJustify, minWidth, zeroPad);
			  }
		case 'e':
		case 'E':
		case 'f':
		case 'F':
		case 'g':
		case 'G':
		          {
			      var number = +value;
			      var prefix = number < 0 ? '-' : positivePrefix;
			      var method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
			      var textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
			      value = prefix + Math.abs(number)[method](precision);
			      return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
			  }
		default: return substring;
	    }
		    });
}
sprintf.regex = /%%|%(\d+\$)?([-+#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;

/**
 * Trival printf implementation, probably only useful during page-load.
 * Note: you may as well use "document.write(sprintf(....))" directly
 */
function printf() {
    // delegate the work to sprintf in an IE5 friendly manner:
    var i = 0, a = arguments, args = Array(arguments.length);
    while (i < args.length) args[i] = 'a[' + (i++) + ']';
    document.write(eval('sprintf(' + args + ')'));
}

//===================================================================================

