//
// Here we have generic HTML, DOM and Browser support functions
//

var mooFormPosted=false;
function BrowserDetection(){
	this.agt=navigator.userAgent.toLowerCase();
	this.browser ='';
	this.version=0;
	this.compleVersion=0;
	this.isIE=false;
	this.isNetscape=false;
	this.isFirefox =false;
	this.isGood = false;
	this.sf =false;
	
	this.isWin=((this.agt.indexOf("win")!=-1)||(this.agt.indexOf("16bit")!=-1));
	this.isMac=(this.agt.indexOf("mac")!=-1);
	this.isLinux = (this.agt.indexOf("linux")!=-1);
	if (navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('AOL')==-1 ){

		this.browser = 'IE'
	 	this.isIE = true;
	 	reg = /(MSIE)(.)(\d+)(.)(\d+)/i
		ar = reg.exec(navigator.userAgent)
		this.version = ar[3]
	 	this.compleVersion = ar[3]+ar[4]+ar[5]
		
	}
	else if (navigator.userAgent.indexOf('Firefox') != -1 ){
		this.browser = 'Firefox'
		this.isFirefox =true;
		reg = /(Firefox)(.)(\d+)(.)(\d+)/i
		ar = reg.exec(navigator.userAgent)
		this.version = ar[3]
		this.compleVersion = ar[3]+ar[4]+ar[5]
		
		
	}
	else if (navigator.userAgent.indexOf('Netscape') != -1 ){
		this.browser = 'Netscape'
		this.isNetscape=true;
		reg = /(Netscape)(.)(\d+)(.)(\d+)/i
		ar = reg.exec(navigator.userAgent)
		this.version = ar[3]
		this.compleVersion = ar[3]+ar[4]+ar[5]
		
	}else if(navigator.userAgent.indexOf("Safari") !=-1){
	
		this.sf=true;
	}
	
	if ((this.isIE && this.version>=5) || (this.isNetscape && this.version >=6) 
	|| (this.isFirefox && this.version >=1)){
	
		this.isGood =true;
	
	}

}
var browser = new BrowserDetection();

var ie4 = (document.all) ? true : false;
var ns4 = (document.layers) ? true : false;
var ns6 = (document.getElementById && !document.all) ? true : false;

function mooElementById(lay){
	if (ie4) return document.all[lay];
	if (ns4) return document.layers[lay];
	if (ns6) return document.getElementById([lay]);
}

function mooPageOnClickTarget(){
    if (ie4) return document.body;
	if (ns4) return null;
	if (ns6) return window;
}

function mooFindObjectPosition(obj){
	
	var x = obj.offsetLeft;
	var y = obj.offsetTop; 
	var width = obj.offsetWidth
	while(obj.offsetParent){ 	
		if(obj == document.getElementsByTagName('body')[0]){
			break;
		} else{ 
			x = x + obj.offsetParent.offsetLeft; 
			y = y + obj.offsetParent.offsetTop; 
			obj = obj.offsetParent; 
		} 
	} 
	this.x = x;
	this.y = y; 
	this.width = width;
	
	return this; 
}

function mooSetFormField(form, name, value){
  document.forms[form][name].value = value;
}

function mooGetFormField(form, name){
  return document.forms[form][name].value;
}

function mooGetFormOptionField(form, name){
  if (document.forms[form][name].selectedIndex >= 0) {
    return document.forms[form][name].options[document.forms[form][name].selectedIndex].value;
  } else {
    return null;
  }
}

function openWindow(url, height, width){

    if(height && width){
		option = 'width='+ width +', height='+ height +', scrollbars=yes,menubar=no,toolbar=no,location=no,status=no,resizable=yes'
	}else{
		option = 'width=640, height=480, scrollbars=yes,menubar=no,toolbar=no,location=no,status=no'
	}
	theWin = window.open(url, '_blank', option);
	theWin.focus();



}





function getLeft(el) {
	currObj = el;
	theOffset = el.offsetLeft;
	while(currObj = currObj.offsetParent) {
		theOffset += currObj.offsetLeft;
	}
	
	return theOffset;
}

function getTop(el) {
	
	currObj = el;
	theOffset = el.offsetTop;
	while(currObj = currObj.offsetParent) {
		theOffset += currObj.offsetTop;
	}
	
	return theOffset;
}

function fadeDiv(elId, obscurDivId){
	try{
	el = document.getElementById(elId)
	obscureDivs = document.getElementById(obscurDivId)
	obscureDivs.style.top = getTop(el) + 'px';
	obscureDivs.style.left = getLeft(el) - 1 + 'px';
	obscureDivs.style.width = el.offsetWidth + 'px';
	obscureDivs.style.height =el.offsetHeight + 1 +   'px';
	obscureDivs.style.display='block';
	}catch(err){}
}
function moveToPosition(obscurDivId, elId , x, y){
	el = document.getElementById(elId)
	obscureDivs = document.getElementById(obscurDivId)
	obscureDivs.style.top = getTop(el)+y 
	obscureDivs.style.left = getLeft(el)+x - 1
}

var mooWindow; 
function mooOpenWindow(url, width, height){

	if(mooWindow && !mooWindow.closed) {
			mooWindow.close();
	}
	mooWindow = window.open(url, "mooWindow", "width="+width + ", height="+height +"menubar=no,resizable=no,status=no, scrollbars=yes" );
	if(window.focus) {
		mooWindow.focus();
	}
	
}

function mooCheckChars(element, max){

	if(element.value.length > max)
	{
		element.value = element.value.substring(0,max)
	}

}

function mooBrowserChecker(url){
	mooAssertSupportedPlatform();
	if(!browser.isGood){
		document.write("<span class='Error Medium'><br>Your current  browser is not ideal for viewing Moola. For a list of recommended browsers, click  <a class='Red' href='"+ url+"'> here </a><br></span>");
	}else{
		if(browser.isMac){
			
			document.write("<span class='Error Medium'><br>MAC USERS: This site is in the process of being optimized for Firefox and Safari. <br> Please note that this process is not yet complete, and that minor display issues may occur.<br></span>");
	
		}
		if(browser.isLinux && !browser.isMac){
			document.write("<span class='Error Medium'><br>LINUX USERS: This site is in the process of being optimized for Linux versions of Firefox <br>(at this time,  Opera and Konqueror are not supported). Please note that this process is not yet complete, and that minor display issues may occur.<br></span>");
		}
	}
	if(!DetectFlashVer(9,0, 115)){
		document.write("<a href='' onclick =\"mooOpenWindow('http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','800','700'); return false;\" class='Red' target=_blank ><img src='/img/misc/login_flash_alert.gif' border='0'></a>");
	}
}

function showLayer(layerId, isInline) {



	try{
	
		if(document.getElementById(layerId).style.visibility.toUpperCase()=="HIDDEN"){
		document.getElementById(layerId).style.visibility="visible"
		return;
	}
	
		if(isInline) {
			document.getElementById(layerId).style.display='inline';
		}
		else {
			document.getElementById(layerId).style.display='table';
		}
	}catch(err){
		//alert(layerId)
	}
}

function toggleLayer(layerId, isInline){
if(document.getElementById(layerId).style.display=="none"){
	showLayer(layerId, isInline);
}else{
	hideLayer(layerId);
}

}

function hideLayer(layerId) {
	
	try{
		if(document.getElementById(layerId).style.visibility.toUpperCase()=="VISIBLE"){
			document.getElementById(layerId).style.visibility="hidden"
			return;
		}

	document.getElementById(layerId).style.display='none';
	}catch(err){
		//alert(layerId)
	}
}

function populateFormDropDownElement(element, theValue, theDefaultValue)

{ 
   if (theValue==null)
   {
       theValue=theDefaultValue
   }
   elementType= element.type;
   if (element.type=="select-one")
   {

       len = element.length
       for (i=0;i<len ;i++ )
        {
            if(element.options[i].value == theValue)
            {
               element.options[i].selected = true;
            }
        }
   }
  
} 


function makeHomePage(url){

if (document.all){
  document.write('<A HREF="javascript:history.go(0);" onClick="this.style.behavior=\'url(#default#homepage)\';this.setHomePage(\'' + url + '\');">');
  document.write('Make this my home page</a>');
}

// If it's Netscape 6, tell user to drag link onto Home button
// Be sure to change the "http://www.YourWebSiteHere.com\"
// to the URL you want them to bookmark.
else if (document.getElementById){
  document.write('<a href="' + url + '">Drag this link onto your Home button to make this your Home Page.</a>');
}

// If it's Netscape 4 or lower, give instructions to set Home Page
else if (document.layers){
  document.write('<b>Make this site your home page:</b><br>- Go to <b>Preferences</b> in the <B>Edit</B> Menu.<br>- Choose <b>Navigator</b> from the list on the left.<br>- Click on the <b>"Use Current Page"</b> button.');
}

// If it's any other browser, for which I don't know the specifications of home paging, display instructions
else {
  
}


}

//if checkbox elem1 is checked, then check all checkbox elem2
function selectAllCheckBoxes(elem1, elem2){
	
	setTo = elem1.checked
	if(elem2.length>1){
		for(n=0; n< elem2.length;n++){
			elem2[n].checked=setTo;
		}	
	}else{
		elem2.checked=setTo;
	}
	
}


function deSelectAllCheckBoxes(elem){
	if(elem!=null){
		if(!elem.length){
			elem.checked=false;
		}else{	
			for(n=0; n< elem.length;n++){
				elem[n].checked=false;
			}	
		}
	}
}

function clearRadio(elem){
	if(elem!=null){
		if(!elem.length){
			elem.checked=false;
		}else{	
			for(n=0; n< elem.length;n++){
				elem[n].checked=false;
			}	
		}
	}
}



function trim(sString){
		while (sString.substring(0,1) == ' '){
			sString = sString.substring(1, sString.length);
		}
		while (sString.substring(sString.length-1, sString.length) == ' ')	{
			sString = sString.substring(0,sString.length-1);
		}
		return sString;
}


function advanceToNext(currentField,nextField, length) {

    if (currentField.value.length == length)
        nextField.focus();
}



function formatCurrency(n, nodollar) {
	var num = n.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) {
		num = "0";
	}
	var sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	var cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents < 10) {
		cents = '0' + cents;
	}
	for(var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
		num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4 * i + 3));
	}
	if(nodollar) {
		return num + '.' + cents;
	}
	else {
		return '$' + num + '.' + cents;
	}
}

function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
    	return r;
	}
}
function placeIt(id, xOffSet,yOffSet) {
	
		(document.getElementById) ? dom = true : dom = false;
	  if (dom && !document.all) {
		  document.getElementById(id).style.top = window.pageYOffset + (window.innerHeight - (window.innerHeight-yOffSet)) + "px";
		  document.getElementById(id).style.left = window.pageXOffset + (window.innerWidth - (window.innerWidth - xOffSet )) + "px";
	
		  }
	  if (document.all) {
		  document.all[id].style.top = document.documentElement.scrollTop + (document.documentElement.clientHeight - (document.documentElement.clientHeight- yOffSet)) + "px";
		  document.all[id].style.left = document.documentElement.scrollLeft + (document.documentElement.clientWidth - (document.documentElement.clientWidth- xOffSet)) + "px";
		  
	  }
	  //window.setTimeout("placeIt()", 10); 
  }

function generateCallback(functionName) {
	var callbackName = 'callback' + randomString(16);

	eval('window.' + callbackName + ' = ' + functionName + ';');
	return callbackName;
}


function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return(randomstring);
}

function capitalizeField(ele){

	specialChars = "";
     	val = ele.value;
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
           newVal += val[c].substring(0,1).toUpperCase() +
			val[c].substring(1,val[c].length);
			if(c<val.length-1){
				newVal+= ' ';
			}
        }

        newVal2 = '';
        val2 = newVal.split('-');
        for(var d=0; d < val2.length; d++) {
           newVal2 += val2[d].substring(0,1).toUpperCase() +
			val2[d].substring(1,val2[d].length)
			if(d<val2.length-1){
				newVal2+= '-';
			}
        }
        ele.value = newVal2;
}
function moveToSceenCenter(divID, xOffSet,yOffSet) {
	   var layLeft;
	   divEle = document.getElementById(divID);
	   if(document.width) {
	   		layLeft= (parseInt(document.width) - parseInt(divEle.style.width)) / 2 + parseInt(xOffSet);
		}
		else {
			layLeft = (parseInt(document.body.clientWidth) - parseInt(divEle.style.width)) / 2 + xOffSet;
		}
	    divEle.style.top = document.body.scrollTop + yOffSet;
		divEle.style.left = layLeft;
}


// Current Page Reference
//copyright Stephen Chapman, 1st Jan 2005
//you may copy this function but please keep the copyright notice with it
function getURL(uri) {
uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
uri.dom = uri.dir; if (uri.dom.substr(0,7) == 'http:\/\/') uri.dom = uri.dom.substr(7);
uri.path = ''; var pos = uri.dom.indexOf('\/'); if (pos > -1) {uri.path = uri.dom.substr(pos+1); uri.dom = uri.dom.substr(0,pos);}
uri.page = location.href.substring(uri.dir.length+1, location.href.length+1);
pos = uri.page.indexOf('?');if (pos > -1) {uri.page = uri.page.substring(0, pos);}
pos = uri.page.indexOf('#');if (pos > -1) {uri.page = uri.page.substring(0, pos);}
uri.ext = ''; pos = uri.page.indexOf('.');if (pos > -1) {uri.ext =uri.page.substring(pos+1); uri.page = uri.page.substr(0,pos);}
uri.file = uri.page;
if (uri.ext != '') uri.file += '.' + uri.ext;
if (uri.file == '') uri.page = 'index';
uri.args = location.search.substr(1).split("?");
return uri;
}

function showActionDiv(url){
	
	document.getElementById("ActionFrame").src = url;
	moveToSceenCenter("ActionDiv", 0,100)
	showLayer("ActionDiv", false)
	return false;
}
function showFrameDiv(url,frameId, frameDivId, blurDiv, yPos){
	y = 60;
	if(!isUndefined(yPos)){ y=yPos}
	
	fadeDiv("LocaMain",blurDiv)
	document.getElementById(frameId).src = url;
	moveToSceenCenter(frameDivId, 0, y)
	showLayer(frameDivId, false)
	return false;
}

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function getDocWidth() {
	
    var D = document;
    return Math.max(
        Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),
        Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),
        Math.max(D.body.clientWidth, D.documentElement.clientWidth)
    );
}
function getElementsByClassName(className)
{
	var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
	var allElements = document.getElementsByTagName("*");
	var results = [];

	var element;
	for (var i = 0; (element = allElements[i]) != null; i++) {
		var elementClass = element.className;
		try{
		if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
			results.push(element);
		}catch(err){
			//alert(elementClass)
		}
	}

	return results;
}
//"3rsdfsfsfsfsdfsfsfsdfsf".wordWrap(10, "\n+", true));
String.prototype.wordWrap = function(m, b, c){
    var i, j, s, r = this.split(" ");
    if(m > 0) for(i in r){
        for(s = r[i], r[i] = ""; s.length > m;
            j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
            || m,
            r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")
        );
        r[i] += s;
       // alert(r[i])
    }
    b = r.join("\n")
    document.write(b);

	
};

function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} 
function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;} 
function setFocus(formName){

	try{
	    for(i=0; i < document.forms[formName].length; i++){
	        if (document.forms[formName][i].type != "hidden"){
	          if (document.forms[formName][i].disabled != true) {
	              document.forms[formName][i].focus();
	              break;
	        }
	      }
	    }
	}catch(err) { }
 }

function showMoreText(str, id){
	document.getElementById(id).innerHTML = str;
}
function addCommas(numberStr){
	str += '';
	x = numberStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function formatNumberToText(num){
	  var isNegative = false;
	  var num2 = Math.abs(num);
	   returnStr ="";
	  
	  if (num<0) isNegative = true;
	  
	  if(num2<10000){
		  returnStr =  num2+"";
	  }
	  
	  if(10000<=num2 && num2<1000000){
		  
		  returnStr = (parseInt(Math.floor(num2/1000))) + "K";
	  }
	  
	  if(1000000<=num2 && num2<1000000000){
		  
		  returnStr = (parseInt(Math.floor(num2/1000000))) + "M";
	  }
	  
	  if(num2>=1000000000){
		  
		  returnStr = (parseInt(Math.floor(num2/1000000))) + "B";
		  
	  }
	  if(isNegative){
		  return "(" + returnStr + ")";
	  }
	  return returnStr;
	  
}
function converTrustScore(num, id){
	
	//alert(id)
	//document.getElementById("search_"+id).innerHTML = formatNumberToText(num)
	
}
function isUndefined(varEle){

	if (undefined != varEle){
		return false;
	}
	return true

}

function getParams(url) {
	url = url.replace(/find/g,"&amp;")
	var idx = url.indexOf('?');
	var tempParams = new Object();
	if (idx != -1) {
		var pairs = url.substring(idx + 1, url.length).split('&');
		for (var i = 0; i < pairs.length; i++) {
			nameVal = pairs[i].split('=');
			tempParams[nameVal[0]] = nameVal[1];
		}
		return tempParams;
	}

}
function html_entity_decode(str) {
	if(!isUndefined(str)){
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
  }
  return "";
}
function initializeStreetView(streetviewURl) {
 
 	params = getParams(streetviewURl)
	cbll = params["cbll"]
	cbp = params["cbp"]
	heading = parseFloat(cbp.split(",")[1])
	streetViewZoom = parseInt(cbp.split(",")[3]) + 1
	streetViewPitch = parseFloat( cbp.split(",")[4]  )
	panoid = params["panoid"]
	layer = params["layer"]
	z =params["z"]
	var sv=Math.floor(Math.random()*99)          
	lat = cbll.split(",")[0]
	lng = cbll.split(",")[1]   
 
    var fenway = new google.maps.LatLng(lat,lng);
    var mapOptions = {
      center: fenway,
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      streetViewControl: true
    };
    var map = new google.maps.Map(
        document.getElementById("map_canvas"), mapOptions);

    var panoramaOptions;
    if(panoid){
       
     	panoramaOptions = {
      		position: fenway,
      		pov: {
        		heading: heading,
        		pitch: streetViewPitch,
        		zoom: streetViewZoom
      		}
    	};
    }else{
    	panoramaOptions = {
    	  
    		      position: fenway,
    		      pov: {
    		        heading: heading,
    		        pitch: streetViewPitch,
    		        zoom: streetViewZoom
    		      }
    		    };
    	}
    var panorama = new  google.maps.StreetViewPanorama(document.getElementById("pano"),panoramaOptions);
    map.setStreetView(panorama);
  }
  function showLanguageForm(){
  	/*document.getElementById("changeViewLink").style.display="inline"
  	document.getElementById("changeViewDiv").style.display="none"
  	
  	document.getElementById("changeLanLink").style.display="none"
  	document.getElementById("lanDiv").style.display="inline"*/
  	
  	moveToPosition("lanDiv", "changeLanLink" , -100, 10)
  	showLayer("lanDiv")
  	document.getElementById("ChooseLanguage").focus()
  	
  
  	
  }
  function showChangeViewForm(){
  /* 	document.getElementById("changeLanLink").style.display="inline"
  	document.getElementById("lanDiv").style.display="none"
  	
  	document.getElementById("changeViewLink").style.display="none"
  	document.getElementById("changeViewDiv").style.display="inline"*/
  	
  	moveToPosition("changeViewDiv", "changeViewLink" , -150, 10)
  	showLayer("changeViewDiv")
  	document.getElementById("ChooseView").focus()
  	
  }


var GeoCodeCalc = {};
GeoCodeCalc.EarthRadiusInMiles = 3956.0;
GeoCodeCalc.EarthRadiusInMeters = 6378137 
GeoCodeCalc.ToRadian = function(v) { return v * (Math.PI / 180);};
GeoCodeCalc.DiffRadian = function(v1, v2) {
return GeoCodeCalc.ToRadian(v2) - GeoCodeCalc.ToRadian(v1);
};
GeoCodeCalc.CalcDistance = function(lat1, lng1, lat2, lng2, radius) {
return radius * 2 * Math.asin( Math.min(1, Math.sqrt( ( Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.cos(GeoCodeCalc.ToRadian(lat1)) * Math.cos(GeoCodeCalc.ToRadian(lat2)) * Math.pow(Math.sin((GeoCodeCalc.DiffRadian(lng1, lng2)) / 2.0), 2.0) ) ) ) );
};


// Calculate distance in Milesvar
//d = GeoCodeCalc.CalcDistance(47.8131545175277, -122.783203125, 42.0982224111897, -87.890625, GeoCodeCalc.EarthRadiusInKilometers);

function showLoading(frameId){
	document.getElementById(frameId).src="/places/loading.jsp"
}


function moveToCenter(divID, yOffSet) {
    if(!isUndefined(yOffSet)){
    	$("#"+divID).css("top", ($(window).scrollTop() + yOffSet) + "px");
    }
    $("#"+divID).css("left", (($(window).width() - $("#"+divID).outerWidth()) / 2) + $(window).scrollLeft() + "px");
}






