function StringBuffer() { 
   this.buffer = []; 
}

StringBuffer.prototype.append = function append(string) { 
   this.buffer.push(string); 
   return this; 
}; 

StringBuffer.prototype.toString = function toString() { 
   return this.buffer.join(""); 
};

function processMobileResponse(req, mobileUrl, uri){   
	var xmlDoc = req.responseXML;
	var mobileTag=xmlDoc.getElementsByTagName("isMobile");
	var isMobile = mobileTag[0].firstChild.nodeValue;

	if (isMobile == 'true') {
		setCookie("isMobile", "true");
		toMobile(mobileUrl, uri);
	} else {
		setCookie("isMobile", "false");
		//do nothing
	}
} 

function isPhoneSized(){
	if ((screen.width<1024) && (screen.height<1024)){
		return true;
	}
	return false;
}

function lookupMobile(mobileBase, pageURI) {
	var mobileCookie = checkMobileCookie();
	//if mob=f, (re)set cookie
	if (window.location.href.indexOf("mob=f") > 1) {
		parms="mob=f";
		toStandard(baseUrl, uri);
		return;
	}

	if (mobileCookie == null){
		var parms = '';
		if (isPhoneSized()){
			parms += "phone=true";
		}
		var myAjax = new Ajax.Request(
			'/checkMobile.jsp', 
			{
				method: 'get', 
				parameters: parms, 
				onSuccess: function(req){
	      			processMobileResponse(req, mobileBase, pageURI)
	    		}
			});
	} else if (mobileCookie == 'true'){
		toMobile(mobileBase, pageURI);
	} else {//mobileCookie == false
		//do nothing
	}
}

//if we've already determined if this device is mobile...don't check again
function checkMobileCookie(){
	return getCookie("isMobile");
}

function toMobile(baseUrl, uri){
	urlParts = baseUrl.split(":");
	if(document.location.href.indexOf(urlParts[1])==-1){
		mobileLocation = (uri=='/')?(baseUrl + "/smartphone"):(baseUrl + uri);
		document.location.href = mobileLocation;
	}
}

function toStandard(baseUrl, uri){
	uri = (uri.indexOf("/smartphone") > -1)?(uri.replace("/smartphone","")):uri;
	uri = (uri.indexOf("/") == 0) ? uri.substring(1): uri;
	setCookie("isMobile", "notNow");
	standardLocation = baseUrl + uri;
	document.location.href = standardLocation;
}

