String.prototype.strip = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

String.prototype.trim = function (len,trail) {
	trail = trail || ' ...';
	if(this.length > len) {
		return this.substr(0, len) + trail;
	} else {
		return this;
	}
};

String.prototype.toUpperCaseWords = function () {
	var words = this.split(" "), tmp = [];
	for(var i=0; i<words.length; i++) {
		tmp[i] = words[i].substr(0,1).toUpperCase() + words[i].substr(1).toLowerCase();
	}
	return tmp.join(" ");
};

//Thank you Brian Wilson for the list of reserved/unsafe characters
String.reservedChars = {
	"HTML": {
		'"': "&#34;",
		"'": "&#39;",
		"&": "&amp;",
		"<": "&lt;",
		">": "&gt;"
	},
	"URL": {
		"$": "%24",
		"&": "%26",
		"+": "%2b",
		",": "%2c",
		"/": "%2f",
		":": "%3a",
		";": "%3b",
		"=": "%3d",
		"?": "%3f",
		"@": "%40",
		" ": "%20",
		'"': "%22",
		"'": "%27",
		"<": "%3c",
		">": "%3e",
		"#": "%23",
		"%": "%25",
		"{": "%7b",
		"}": "%7d",
		"|": "%7c",
		"\\":"%5c",
		"^": "%5e",
		"~": "%7e",
		"[": "%5b",
		"]": "%5d",
		"`": "%60",
		"€": "%80" //NOTE: &#128; is a windows bug!
	}
};

String.prototype.encodeHTML = function () {
	var str = this, code, tmp = "";
	for(var i=0; i<str.length; i++) {
		code = str.charCodeAt(i);
		if((code>=0x00 && code<=0x1F) || (code>=0x7F && code<=0x9F)) {
			tmp += '&#' + code + ';';
		} else if(code>=0xA0 && code<=0xFF) {
			tmp += '&#' + code + ';';
		} else if(str.charAt(i) in String.reservedChars.HTML) {
			tmp += String.reservedChars.HTML[str.charAt(i)];
		} else {
			tmp += str.charAt(i);
		}
	}
	return tmp;
};

String.prototype.decodeHTML = function () {
	var str = this, code, tmp = "";
	for(var i=0; i<str.length; i++) {
		if(str.charAt(i) === '&') {
			code = '';
			for(i=i+1;str.charAt(i)!==';' && i<str.length;i++) {
				code += str.charAt(i);
			}
			//NOTE: for loop will do the final increment
			tmp += String.fromCharCode(code);
		} else {
			tmp += str.charAt(i);
		}
	}
	return tmp;
};

String.prototype.encodeURL = function () {
	var str = this, code, tmp = "";
	for(var i=0; i<str.length; i++) {
		code = str.charCodeAt(i);
		if((code>=0x00 && code<=0x1F) || (code==0x7F)) { //ASCII Control characters
			tmp += ((code < 0x10) ? '%0' : '%') + code.toString(16);
		} else if(code>=0x80 && code<=0xFF) { //Non-ASCII characters
			tmp += '%' + code.toString(16);
		} else if(str.charAt(i) in String.reservedChars.URL) { // Reserved and Unsafe characters
			tmp += String.reservedChars.URL[str.charAt(i)];
		} else {
			tmp += str.charAt(i);
		}
	}
	return tmp;
};

String.prototype.decodeURL = function () {
	var str = this, code, tmp = "";
	for(var i=0; i<str.length; i++) {
		if(str.charAt(i) === '%') {
			if(i+2 < str.length) { //accept only encoded URLs of the form %XX
				code = parseInt(str.charAt(i+1) + str.charAt(i+2), 16);
				if(code===128) {
					code = 8364; //XXX: € is 8364 and not 128
				}
				tmp += String.fromCharCode(code);
				i += 2; //NOTE: for loop will do the thrid increment
			}
		} else if(str.charAt(i) === '+') {
			tmp += ' ';
		} else {
			tmp += str.charAt(i);
		}
	}
	return tmp;
};

function getQueryStringParameter(paramName, url) {
	var i, len, idx, queryString, params, tokens;

	url = url || top.location.href;

	idx = url.indexOf("?");
	queryString = idx >= 0 ? url.substr(idx + 1) : url;

	// Remove the hash if any
	idx = queryString.lastIndexOf("#");
	queryString = idx >= 0 ? queryString.substr(0, idx) : queryString;

	params = queryString.split("&");

	for (i = 0, len = params.length; i < len; i++) {
		tokens = params[i].split("=");
		if (tokens.length >= 2) {
			if (tokens[0] === paramName) {
				return tokens[1].decodeURL();
			}
		}
	}

	return null;
}

function inArray(arr,val) {
	for(var i=0; i<arr.length; i++) {
		if(arr[i] === val) {
			return true;
		}
	}
	return false;
}

function preloadImage(src) {
	(new Image()).src = src;
}

//checks if the parameter is a valid AlamyRef
function isAlamyRef(aref) {
	return (new RegExp("^[A-B]([0-9A-FO]{5}|[GHJKMNPR-TW-Y][0-9A-FO]{4}|[0-9A-HJKMNPRSTXWYO][GHJKMNPR-TW-Y][0-9A-FO]{3}|[0-9A-HJKMNPRSTXWYO]{2}[GHJKMNPR-TW-Y][0-9A-FO]{2}|[0-9A-HJKMNPRSTXWYO]{3}[GHJKMNPR-TW-Y][0-9A-FO]{1}|[0-9A-HJKMNPRSTXWYO]{4}[GHJKMNPR-TW-Y])$", "i")).test(aref);
}

function redirectPage(redirectTo, returnParams) {
	var query = (alamy_search) ? alamy_search._query.getQuery() : '',
		returnURL = top.location.protocol + "//" + top.location.hostname + top.location.pathname +
			'?' + query + '&srch=' + query.encodeURL() + (returnParams || '');
	top.location.href = redirectTo + "?returnurl=" + returnURL.encodeURL();
}

function jumpPage(jumpTo) {
	var query = (alamy_search) ? alamy_search._query.getQuery() : '';
	top.location.href = jumpTo + "?srch=" + query.encodeURL();
}

function popupImageDetails(imageID, pseudoID, offset, queryString) {
	var popup_src = "image-details-popup.asp?pv=1&stamp=2" +
					"&imageid=" + imageID +
					"&p=" + pseudoID +
					"&n=" + offset +
					(queryString || ""),
		popup_width  = 850,
		popup_height = 615,
		popup_left = (screen.width  - popup_width)  / 2,
		popup_top  = (screen.height - popup_height) / 2 - 20;
	window.open(popup_src, "",
		"alwaysRaised=yes,resizable=yes,location=0,directories=0,menubar=0,toolbar=0,status=0,scrollbars=1,copyhistory=0" +
		",width="+popup_width +
		",height="+popup_height +
		",left="+popup_left +
		",top="+popup_top);
}

function clearWindowStatus(o) {
	window.status = "";
}

function addHelper(url, args, msg, cmd, canAdd) {
	var params = [], a;
	for(a in args) {
		params[params.length] = a + '=' + args[a];
	}
	params = params.join('&');
	
	if(canAdd() === true) {
		window.status = msg;
		YAHOO.util.Connect.asyncRequest('GET', url + params, {
			success:clearWindowStatus,
			failure:clearWindowStatus,
			cache:false
		});
	} else {
		redirectPage(urlLogin, "&cmd="+cmd+'&'+params);
	}
}

function canAddToLightBox() {
	var userID = YAHOO.util.Cookie.get("AlamyUserID",{raw:true}) || "";
	return (userID.length > 0);
}

function canAddToShoppingCart() {
	var userID = YAHOO.util.Cookie.get("AlamyUserID",{raw:true}) || "";
	if(intranetMode != 1) {
		if(userID.length === 0) { userID = YAHOO.util.Cookie.get("UID",    {raw:true}) || ""; }
		if(userID.length === 0) { userID = YAHOO.util.Cookie.get("Session",{raw:true}) || ""; }
	}
	return (userID.length > 0);
}

function addImageToLightBox(imageID, lightboxID, collectionID) {
	addHelper("add-to-lightbox.asp?",
		{"imageid": imageID,"clbid": lightboxID,"collid": collectionID},
		"Adding image to Lightbox...",
		"add2lb",
		canAddToLightBox);
}

function addImageToShoppingCart(imageID, collectionID) {
	addHelper("add-to-basket.asp?",
		{"imageid": imageID,"collid": collectionID},
		"Adding image to Shopping Cart...",
		"add2basket",
		canAddToShoppingCart);
}

function addCDToLightBox(cdID, lightboxID) {
	addHelper("add-CD-to-lightbox.asp?",
		{"cdid": cdID,"clbid": lightboxID},
		"Adding CD to Lightbox...",
		"addcd2lb",
		canAddToLightBox);
}

function addCDToShoppingCart(cdID) {
	addHelper("add-CD-to-basket.asp?",
		{"cdid": cdID},
		"Adding CD to Shopping Cart...",
		"addCD2basket",
		canAddToShoppingCart);
}

function changeCurrentLightBox(idx) {
	//NOTE: executing context is a "select" control
	var lightboxID = this[idx].value;
	if(lightboxID === "NOLIGHTBOX") {
		alert("Please select a lightbox");
		this.selectedIndex = currentLightBox;
		return false;
	} else {
		addHelper("set-current-lightbox.asp?",
			{"clbid": lightboxID},
			"Changing current Lightbox...",
			"", //NOTE: cmd is used only if canAdd() returns false
			function(){return true;});
		return true;
	}
}

//NOTE: Is there a reason to continue adding this bit of Dreamweaver code?
function MM_reloadPage(init) { //reloads the window if Nav4 resized
	if (init == true) {
		if ((navigator.appName == "Netscape") && (parseInt(navigator.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);

