var listingDetail;//main object
var panelw=0;
var panelh=0;

var htmlDetailPage=false;
var htmlW=700;
var htmlH=800;
var htmlTop=0;
var htmlLeft=0;

var curWidget='';

//store current widget stage properties to prevent an unneccessary re-load of data on tab/panel return
var curlat=0; var curlon=0; //for streetview
var curZip=0;//for schools
var currentZillowURL='';//for zillow
var currentWalkscoreAddress='';//for walkscore

//stuff for walkscore
var ws_wsid = 'f650d8dd493b0d987db665ca5445a8ad'; var ws_address = ''; var ws_width = '690'; var ws_height = '286';  var ws_force_layout = 'horizontal'; var ws_setParams='';
var ws_paramTemplate='wsid=f650d8dd493b0d987db665ca5445a8ad&street=ADDRESS&width=690&layout=horizontal';

//stuff for education.com schools widget
var educationKey='b95c6932f8cb6519ed8ffd295ecd27c8';

//set the detail object from flex
function setListingDetail(theObj){
    listingDetail=theObj;

    //set up walkscore stuff
    ws_address = listingDetail.walkscoreAddr;
    ws_address=ws_address.split("  ").join(" ").split(" ,").join(",").split(" ").join("%20");
    ws_setParams=ws_paramTemplate.split("ADDRESS").join(ws_address);
    
    //set up zillow stuff
    zillowURL='/kansas/assets/zillow.php?city='+listingDetail.CIT+'&zip='+listingDetail.ZIP+'&dsr='+listingDetail.DSR;
    zillowURL=zillowURL.split(" ").join("%20");
    
    if (htmlDetailPage==true){
        var pWrap=document.getElementById('panoWrap');
        var oWrap=document.getElementById('overviewWrap');
        pWrap.style.margin=0;
        pWrap.style.top=oWrap.offsetTop+'px';
        pWrap.style.left=oWrap.offsetLeft+'px';
        setPanorama(listingDetail.LATI,listingDetail.XLONG,oWrap.offsetWidth,550);
        makeThumbnails();
    }
}


//stuff for street view
var myPano; var panoClient;

function initializeStreetView() {
  myPano = new GStreetviewPanorama(document.getElementById("pano"));
  GEvent.addListener(myPano, "error", handleNoFlash);
  panoClient = new GStreetviewClient();  
}

function handleNoFlash(errorCode) {
  if (errorCode == FLASH_UNAVAILABLE) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}


function showPanoData(panoData){
    if (panoData.code != 200) {
        if (htmlDetailPage==false){
           getFlashMovie("kansasFlash").streetViewExists("false");
        }else{
           document.getElementById('streetViewLink').style.display='none';
        }
    }else{
        if (htmlDetailPage==false){
           getFlashMovie("kansasFlash").streetViewExists("true");
        }
        var listingLatLon  = new GLatLng(curlat,curlon);
        var thePOV = {yaw:0,pitch:0};
        myPano.setLocationAndPOV(listingLatLon, thePOV); 
    }
}

function setPanorama(lat,lon,w,h)
{
	if (lat!=curlat && lon!=curlon){
		sizeDiv("panoWrap",w,h,0);
        sizeDiv("pano",w,h,0);
        curlat=lat;
        curlon=lon;
        var listingLatLon  = new GLatLng(lat,lon);
        panoClient.getNearestPanorama(listingLatLon, showPanoData);
    }
}

function showPano(toggle,topOffset){
	document.getElementById("pano").style.paddingTop=topOffset+'px';
   	toggleOverlayContent("pano",toggle);
}

function getFlashMovie(movieName) {
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
	//if (isIE){movieName=movieName+'IE';}
    return (isIE) ? window[movieName] : document.getElementsByName(movieName)[0];
}
//end street view stuff


//stuff for html detail page
function showPanel(sel){
    var oWrap=document.getElementById('overviewWrap');
    
    showWidget('dummy',false,0,0,0);
    showPano(false,0);
    
    if (sel!='overview'){
        oWrap.style.visibility='hidden';       
    }
    switch (sel){
        case 'overview':
            oWrap.style.visibility='visible';   
        break;
        case 'streetView':
            showPano(true,0);
        break;
        default:
            showWidget(sel,true,oWrap.offsetWidth,oWrap.offsetHeight,0);
        break;
    }
}
function popMap(address){
    window.open('http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='+address+'&ie=UTF8&hq=&hnear='+address+'&z=16&iwloc=A&output=embed','popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=600,height=500,screenX=100,screenY=100,top=100,left=100');
}

//container utilities
function toggleOverlayContent(theDiv,toggle){
	    var oDiv=document.getElementById(theDiv+"Wrap");
    	switch (toggle){
        	case true:  oDiv.style.display="block";break;
        	case false: oDiv.style.display="none";break;
	    }
}
function sizeDiv(theDiv,w,h,topOffset){
   //alert (theDiv);
    panelw=w;
    panelh=h;
    //alert (document.getElementById(theDiv));
	var cDiv=document.getElementById(theDiv);   

    if (htmlDetailPage==true){
        var oWrap=document.getElementById('overviewWrap');
        cDiv.style.margin=0+'px';
        cDiv.style.top=oWrap.offsetTop+'px';
        cDiv.style.left=oWrap.offsetLeft+'px';
    }else{
	   cDiv.style.paddingTop=topOffset+'px';
    }
    cDiv.style.width=w+'px';
    cDiv.style.height=h+'px';
    
}


//print flyer
function printFlyer(LN) {
    var winLeft = (window.screen.width/2) - (360);
    var winTop = (window.screen.height/2) - (400);
    var pop = window.open("/flyer/"+LN,"Print_Flyer","status=no,height=700,width=720,resizable=yes,left=" + winLeft + ",top=" + winTop + ",screenX=" + winLeft + ",screenY=" + winTop + ",toolbar=no,menubar=no,scrollbars=yes,location=no,directories=no");
    pop.focus();
}


//widgets
function showWidget(widget,toggle,w,h,topOffset){
	if (toggle==true){
		sizeDiv("widgetsWrap",w,h,topOffset);
		sizeDiv(widget,w,h,0);
		toggleWidgetContent(widget,toggle);
	}
	toggleOverlayContent("widgets",toggle);
}
function toggleWidgetContent(widget,toggle){      
    document.getElementById("trends").style.display="none";
    document.getElementById("nearby").style.display="none";
    document.getElementById("schools").style.display="none";
    if (toggle==true){
        makeWidgetContent(widget);
        document.getElementById(widget).style.display="block";
    }
}
function makeWidgetContent(widget){
    var html;
    switch(widget){
        case 'schools':
            if (curZip!=listingDetail.ZIP){
                schoolw=panelw-50;
                schoolh=panelh-140;
                document.getElementById("schools").innerHTML='<span class="smallhead">Loading local area schools</span>';
                document.getElementById("schools").innerHTML='<div><div id="widget"><ul style="list-style: none; display:block;float:left;padding:0;margin:0;"><li class="tab">View results as </li><li class="tab selected-tab" id="maptab"><a href="#" OnClick="javascript: updateTab(\'maptab\');return false;">map</a></li><li class="tab" id="datatab"><a href="#" OnClick="javascript:updateTab(\'datatab\');document.getElementById(\'tablecontentframe\').src=\'http://www.education.com/widget/schoolfinder/SF_SearchResults.php?widget_key='+educationKey+'&widget_searchterm='+listingDetail.ZIP+'&widget_searchterm_stadd=&search_type=searchbyaddress&height=500\';return false;">list</a></li> </ul> </div> <div style="clear:both"></div> <div id="mapcontent"  class="tabContent" style="width:'+schoolw+'px;height:'+schoolh+'px;">  <iframe width="100%" height="100%" frameborder=0 src="http://www.education.com/widget/schoolfinder/map.php?widget_key='+educationKey+'&widget_searchterm='+listingDetail.ZIP+'&widget_searchterm_stadd=&search_type=searchbyaddress">   Loading map....  </iframe> </div> <div id="tablecontent" class="tabContent" style="width:'+schoolw+'px;height:'+schoolh+'px;display:none;">  <iframe name="tablecontentframe" id="tablecontentframe" width="100%" height="100%" frameborder=0 src="http://www.education.com/themes/sky/i/schoolfinder/images/ajax_loading_content.gif">  </iframe> </div> <div style="margin: 5px 5px 0px 5px;">     <div id="bottom-school-links" style="float:left;font-size:10px;font-family:verdana;width:510px;">                <a target="_blank" style="float: none; text-decoration: none;" href="http://www.education.com/schoolfinder/us/washington/'+listingDetail.CIT+'/">Browse '+listingDetail.CIT+' Schools </a><br>          <a target="_blank" style="text-decoration: none;" href="http://www.education.com/schoolfinder/us/washington/">Browse Washington Schools </a><br>      </div>         <div id="bottom-links-right" style="float:right;">   <a href=\'http://www.education.com/schoolfinder\' target=\'_blank\'><img src="http://www.education.com/i/logo/edu-logo-150x32.jpg" border="0" alt="Provided by Education.com"></a>  </div>  <div style="clear:both"></div> </div> </div><!--Local Schools Widget Ends here-->';
                curZip=listingDetail.ZIP;
            }
        break;
        case 'nearby':
            if (currentWalkscoreAddress!=ws_address){
               document.getElementById("ws-walkscore-tile").innerHTML="";
               ws_show_tile(ws_width, ws_layout, ws_height, ws_hide_footer, ws_setParams);
               currentWalkscoreAddress=ws_address;
            }
        break;
        case 'trends':
            if (currentZillowURL!=zillowURL){
                //alert (zillowURL);
                document.getElementById("trends").innerHTML='<span class="smallhead">Loading price trends and demographic data</span>';
                ajaxpage(zillowURL,'trends');
                currentZillowURL=zillowURL;
            }
        break;
    }
    return html;
}

    
//scripts for schools widget
function updateTab(tabName)  {   if(tabName=='maptab')   {   setClassName('maptab','tab selected-tab');   setClassName('datatab','tab');     hideDiv('mapcontent',false);   hideDiv('tablecontent',true);    }   else if(tabName=='datatab')   {   setClassName('maptab','tab');   setClassName('datatab','tab selected-tab');     hideDiv('mapcontent',true);   hideDiv('tablecontent',false);    }     }  function setClassName(CompID,ClName)  {   document.getElementById(CompID).className=ClName;  }  function hideDiv(DivID,isHidden)  {   if(isHidden)    document.getElementById(DivID).style.display="none";   else    document.getElementById(DivID).style.display="";  }


//thumbnails for html detail page
function makeThumbnails(){
    var tnDiv=document.getElementById('thumbNails');
    var html='';
    for (var c=0; c<listingDetail.photos.length; c++){
        html+='<a onmouseover="swapPic(\''+listingDetail.photos[c].fullImage+'\');"><img src="'+listingDetail.photos[c].fullImage+'" class="thumb" border="0" width="50" height="50" alt="0"></a>&nbsp;';
    }
    tnDiv.innerHTML=html;
}
function swapPic(pic){
    var pImg=document.getElementById('largePhoto');
    var hImg=document.getElementById('imageHolder');
    hImg.src=pic;
    pImg.src=pic;
    if (hImg.height>275){
        var newdim=getNewImageSize(hImg,400,275);
        pImg.width=newdim[0];
        pImg.height=newdim[1];
    }else{
        pImg.width=hImg.width;
        pImg.height=hImg.height;
    }    
}
function getNewImageSize(img,max_width,max_height){
    var width=img.width;
    var height=img.height;
    var newwidth=0;
    var newheight=0;
    
    if (width>height){
        newwidth=max_width;
        newheight=(height/width)*max_width;
    }else{
        newheight=max_height;
        newwidth=(width/height)*max_height;
    }
    if (newheight>max_height){
        newheight=max_height;
        newwidth=(width/height)*max_height;
    }
    if (newwidth>max_width){
        newwidth=max_width;
        newheight=(height/width)*max_width;
    }
    var newdim=[Math.floor(newwidth),Math.floor(newheight)];
   return newdim;
}    

//ajax script
var loadedobjects=""
var rootdomain="http://"+window.location.hostname    
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest)
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
page_request.open('GET', url, true)
page_request.send(null)
}    
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

