/**
 *  mod_homepage.js:
 *
 *  Last Checked In By $Author: sasman $
 *  $Date: 2005/03/17 22:18:28 $
 *  $Revision: 1.30 $
 *
 *  (c) 2004 Copyright Basis Applied Technology
 *  CONFIDENTIAL INFORMATION
 *  All rights are reserved. Copying or other reproduction of
 *  this program except for archival purposes is prohibited
 *  without the prior written consent of Basis Applied Technology
 *
 *  Basis Applied Technology
 *  Gibsons, BC
 *  604.886.0721
 *
 *  REVISION HISTORY
 */
//GLOBALS

HomePageManager = new Object();

/**
*/
HomePageManager.Init = function( obj )
{
//@TODO: This url needs to be specified from the server
	this.baseUrl = obj.baseUrl;

	this.server = obj.server;
	this.listingServer = obj.listingServer;
	this.adServer = obj.adServer;
	this.mapServer = obj.mapServer;
    this.mapInsetId = obj.mapInsetId;
    this.mapSize = obj.mapSize;
	this.view = obj.view;
	this.page = obj.page;
	this.listingId = obj.listingId;
	this.itemId = obj.itemId;
	this.subItemId = -1;

    this.centerFrame =  document.getElementById( "CenterFrame" );
    this.centerFrame2 =  document.getElementById( "CenterFrame2" );
    this.locationDropDown = document.getElementById( "LocationDropDown" );
    this.locationDropDown.onchange = function(){ HomePageManager.onLocationChange(); }
    this.locationTable = document.getElementById( "LocationTable" );
    this.adFrame =  document.getElementById( "AdFrame" );
    this.croftImageP =  document.getElementById( "CroftImage" );
    this.croftDiv =  document.getElementById( "CroftDiv" );

/*
    this.prevCenterFrameContent =  "";
    this.prevCenterFrameWidth = 0;
*/

    this.find =  document.getElementById( "FindKeywordButton" );
    this.find.onclick = function(){ HomePageManager.onFind(); }
    this.keywords =  document.getElementById( "Keywords" );
    this.mapInsetTD =  document.getElementById( "MapInsetTD" );
    this.leftNavContainerTD =  document.getElementById( "LeftNavContainerTD" );
    //this.onItemClicked = function(id ){HomePageManager.onItemClick( id );};
    //this.onSubItemClicked = function(id ){HomePageManager.onSubItemClick( id );};

    this.mapInsetImg = core.getElm(this.mapInsetId);

    if(this.mapInsetImg)
    {
        if(core.isIE)
            this.mapInsetImg.onmousedown = function(){HomePageManager.onMapMouseDown();};
        else
            this.mapInsetImg.addEventListener("mousedown", HomePageManager.onMapMouseDown, false);
    }

	this.selectedTab = 0;

    if( this.view == "SCPage" ) {
		//this.pageDropDown = document.getElementById( "CroftPageDropDown" );
		//this.pageDropDown.onchange = function(){ HomePageManager.onPageChange(); }
	}



    if( this.view == "Listings" ) {
    	if( parseInt( this.itemId ) > -1 ) {
			this.onSubItemClick( this.itemId );
		} else { //must be a search
			this.keyword = obj.keyword;
			this.FindListings( this.keyword )
		}
	} else
    if( this.view == "Business" ) {
		this.GetListingPage( this.listingId, 0 );
	} else
	if( this.page > -1 ) {
     	this.GetPage( this.page );
	}
    return this;
};
// -----------------------------------------------------------------
HomePageManager.GetPage = function ( id )
{
	if( this.view == "Map" ) {
		//spoofing HOME for now
		window.location.href = "index.php?page=" + id;
		return;
	}

    if (this.mPacket) {
        this.mPacket.Abort();
        this.mPacket = null;
    }
    var cb = new Functor(this, this.GetPageResult, [id]);
    // server, key, method, args, context, async, functor, informat, outformat
	this.mPacket = app.xmlrpc.Call(this.server, base.key, 'Home.GetHeadingPage', [id], 0, true, cb);

    this.setAsyncText('Loading...');
    this.locationTable.style.display = "none";
}

// -----------------------------------------------------------------
HomePageManager.GetPageResult = function ( id, response ) {
    if (response !== undefined) {
        this.mPacket = null;
        if (response instanceof XMLRPCFault) {
            base._handleFault(response);
        } else {

            urchinTracker('/page/'+id);

            this.page = id;
            this.mapInsetTD.style.display="inline";
            this.centerFrame.innerHTML = response['html'];

              // content object initialization
              var aCobs = response['cobs'];
            for (var i=0;i<aCobs.length;i++)
            {core.getElm(aCobs[i][1]).innerHTML = '';}

            for (var i=0;i<aCobs.length;i++)
            {
               var oCob = base.createCob(aCobs[i][0], core.getElm(aCobs[i][1]));
               oCob.setEditIcon(false);
            };

              this.locationTable.style.display = "none";
            if( this.view == "SCPage" ) {
                mapButton = document.getElementById("MapButton");
                mapButton.onclick = function(){ HomePageManager.onMapButtonClick(); }
                this.croftMapLoaded = false; //map for this page not loaded yet
            }
        }
    }
}

// -----------------------------------------------------------------
HomePageManager.onItemClick = function(  pageId, itemId, index )
{
    if( this.view == "SCPage" ) {
		//this.pageDropDown.style.display = "none";
		this.croftImageP.style.display = "block";
	} else
    if( this.view == "Map" ) {

        window.location.href = "index.php?obj=Home&page=" + pageId + "&leftnav="+index;
        return;
	}

    var disp = (itemId==43 ? 'block' : 'none');
    var div;
    if (div=core.getElm('CroftDropDownDiv'))div.style.display = disp;
    if (div=core.getElm('CroftImageDiv'))div.style.display = disp;
    //this.croftDiv.style.display = disp;

	this.view = "Default";
	this.GetPage( pageId );
	//get the ads
	this.GetAds( itemId );
	this.RestoreListings();
	this.locationTable.style.display = "none";

};

// -----------------------------------------------------------------
HomePageManager.onPageChange = function()
{
  	select = this.pageDropDown;
  	pageId = select.options[select.selectedIndex].value;
	this.GetPage( pageId );

};

// -----------------------------------------------------------------
HomePageManager.onMapMouseDown = function(evt)
{
    //alert("Map Mouse Down X =" + event.offsetX + " Y = " + event.offsetY );
    var iX = 0;
    var iY = 0;

    if(core.isIE)
    {
        iX = event.offsetX;
        iY = event.offsetY;
    }
    else
    {
        iX = evt.layerX;
        iY = evt.layerY;
    }

    var sUrl = 'index.php?obj=Home&view=Map&X=' + iX + '&Y=' + iY + '&map_size=' + HomePageManager.mapSize ;
    window.location.href = sUrl;
}

// -----------------------------------------------------------------
HomePageManager.onMapButtonClick = function()
{

	if( !this.croftMapLoaded ) {

	  	//alert("Loading Croft Page Map, page=" + this.page );

		var response = core.xmlrpc.Call(this.mapServer, base.key, 'Map.GetCroftPageMap', [ this.page ]);

		if (response instanceof XMLRPCFault)
		{
			base._handleFault(response);
		}
		else
		{
			//alert(response);
	    	this.centerFrame2.innerHTML = response;
			this.centerFrame.style.display = "none";
            this.mapInsetTD.style.display="none";
			this.centerFrame2.style.display = "block";
	        backButton = document.getElementById("BackButton");
			backButton.onclick = function(){ HomePageManager.onBackButtonClick(); }
	        mapIdHidden = document.getElementById("MapId");
	        mapId = mapIdHidden.value;

   	        xHidden = document.getElementById("MapX");
	        mapX = xHidden.value;
	        yHidden = document.getElementById("MapY");
	        mapY = yHidden.value;

   	        latHidden = document.getElementById("MapLat");
   	        fLat = latHidden.value;

   	        longHidden = document.getElementById("MapLong");
   	        fLong = longHidden.value;

			obj = new Object();
	    	obj.listingServer = this.listingServer;
	   		obj.mapServer = this.mapServer;
	   		obj.id = mapId;
	   		obj.X = mapX;
	   		obj.Y = mapY;
	   		obj.lat = fLat;
	   		obj.lon = fLong;
	   		obj.pageId = this.page;
	   		obj.pageTitle = this.pageTitle;
			MapManager.Init( obj );
			MapManager.UpdateListingPosition();

			this.croftMapLoaded = true; //map for this page not loaded yet

		}
	}
};

// -----------------------------------------------------------------
HomePageManager.onBackButtonClick = function()
{
    this.mapInsetTD.style.display="block";
	this.centerFrame.style.display = "block";
	this.centerFrame2.style.display = "none";

};


// -----------------------------------------------------------------
HomePageManager.FindListings = function ( keyword )
{
    if( this.view == "Map" ) { //need to reload the home page
		window.location.href = "index.php?obj=Home&view=Listings&search=" + keyword;
     	return;
	}
	var response = core.xmlrpc.Call(this.listingServer, base.key, 'Listing.ViewFindListings', [ keyword ]);

	if (response instanceof XMLRPCFault)
	{
		base._handleFault(response);
	}
	else
	{
		if( response['html'].length == 0 ) {
	    	alert( "No results found for keyword '"+ keyword + "'" );
		} else {
    		this.centerFrame.innerHTML = response['html'];
            this.mapInsetTD.style.display="inline";
            this.trackArray('/listing/', response['ids']);
		}
	}

}

HomePageManager.GetListingsByLocation = function ( id ) {
    if (this.mListingPacket) {
        this.mListingPacket.Abort();
        this.mListingPacket = null;
    }
    var cb = new Functor(this, this.GetListingsResult, [this.subItemId, id]);
    this.mListingPacket = app.xmlrpc.Call(this.listingServer, base.key, 'Listing.ViewLocationListings', [id, this.subItemId], 0, true, cb);
    this.setAsyncText('Searching...');
}

// -----------------------------------------------------------------
HomePageManager.setAsyncText = function (txt) {
    var img = '<img alt="'+txt+'" width="16" height="15" src="/images/spinner.gif" />';
    this.centerFrame.innerHTML = '<div style="text-align:center;padding-top:20px;">'+txt+'<br /><br />'+img+'</div>';
};
// -----------------------------------------------------------------
HomePageManager.setResultsText = function (txt) {
    this.centerFrame.innerHTML = '<div style="text-align:center;padding-top:20px;">'+txt+'</div>';
};

// -----------------------------------------------------------------
HomePageManager.GetListings = function ( id ) {
    this.setAsyncText('Searching...');
    if (this.mListingPacket) {
        this.mListingPacket.Abort();
        this.mListingPacket = null;
    }
    var cb = new Functor(this, this.GetListingsResult, [id, -1]);
    this.mListingPacket = app.xmlrpc.Call(this.listingServer, base.key, 'Listing.ViewCategoryListings', [id], 0, true, cb);
}

HomePageManager.trackArray = function(pfx, ids) {
    for(var i=0;i<ids.length;i++) {
        urchinTracker(pfx+ids[i]);
    }
}

HomePageManager.GetListingsResult = function ( itemID, locationId, response ) {
    this.centerFrame.innerHTML = '';
    if (response !== undefined) {
        this.mListingPacket = null;
        if (response instanceof XMLRPCFault) {
            base._handleFault(response);
        } else {
            this.trackArray('/listing/', response['ids']);

            this.centerFrame.innerHTML = response['html'];
            this.mapInsetTD.style.display="inline";

            if (locationId != -1) {
                if( response['html'].length == 0 ) {
                    this.setResultsText( "No results found for location '"+ this.locationDropDown.options[ this.locationDropDown.selectedIndex].innerText + "'" );
                }
            } else {
                if( response['html'].length == 0 ) {
                    this.setResultsText( "No results found" );
                }
                this.locationTable.style.display = "inline";
            }
        }
    }
}
HomePageManager.GetAds = function ( id ) {
    if (this.mAdPacket) {
        this.mAdPacket.Abort();
        this.mAdPacket=null;
    }
    var cb = new Functor(this, this.GetAdsResult);
    this.mAdPacket = app.xmlrpc.Call(this.adServer, base.key, 'Advertisement.ViewAds', [id], 0, true, cb);
}
// -----------------------------------------------------------------
HomePageManager.GetAdsResult = function ( response ) {
    if (response !== undefined) {
        this.mAdPacket = null;
        if (response instanceof XMLRPCFault) {
            base._handleFault(response);
        }
        else {
            this.adFrame.innerHTML = response['html'];
            this.trackArray('/ad/', response['ids']);
        }
    }
}

// -----------------------------------------------------------------
HomePageManager.GetListingPage = function ( listingId, tab )
{
	var response = core.xmlrpc.Call(this.listingServer, base.key, 'Listing.ViewPage', [ listingId, tab ]);

	if (response instanceof XMLRPCFault)
	{
		base._handleFault(response);
	}
	else
	{
        urchinTracker('/listingpage/'+listingId);

		//alert( response );
        this.mapInsetTD.style.display="none";
  		this.centerFrame.style.display="none";
  		this.centerFrame2.style.width = 500;
  		this.centerFrame2.style.display = "block";
  		this.centerFrame2.innerHTML = response;
  		this.locationTable.style.display = "none";
/*
		this.prevCenterFrameContent = this.centerFrame.innerHTML;
		this.prevCenterFrameWidth = this.centerFrame.style.width
		this.centerFrame.style.width= 500;
		this.centerFrame.innerHTML = response;
*/
		this.listingId = listingId;
		tabTitle = document.getElementById( "PageTabTitle" + tab );
		if (tabTitle)
		{
		    tabTitle.className= "TD_PageTabTitleSelected";
		    this.selectedTab = tab;
		}
	    else // only if it's a street index. @hack
	    {
		    var obj = new Object();
    	    obj.listingServer = this.listingServer;
   		    obj.mapServer = this.mapServer;
   		    obj.pageId = listingId;
		    MapManager.Init( obj );
	    }
	}
}

// -----------------------------------------------------------------
HomePageManager.RestoreListings = function()
{
    this.mapInsetTD.style.display="inline";
	this.centerFrame.style.display="inline";
	this.centerFrame2.style.display = "none";
}

// -----------------------------------------------------------------
HomePageManager.GetPageTab = function ( pageId, tab )
{
	//alert("Server = " + this.listingServer);
	var response = core.xmlrpc.Call(this.listingServer, base.key, 'Listing.ViewPageTab', [ this.listingId, pageId, tab ]);

	if (response instanceof XMLRPCFault)
	{
		base._handleFault(response);
	}
	else
	{
		//alert( response );
		tabTD = document.getElementById( "PageTab");
		tabTD.innerHTML = response;
		//unselect old tab
		tabTitle = document.getElementById( "PageTabTitle" + this.selectedTab );
		tabTitle.className= "TD_PageTabTitle";
		//select new one
		this.selectedTab = tab;
		tabTitle = document.getElementById( "PageTabTitle" + this.selectedTab );
		tabTitle.className= "TD_PageTabTitleSelected";
	}

}

// -----------------------------------------------------------------
HomePageManager.onSubItemClick = function( id )
{

  	//alert("onSubItemClick: "+ id  );
    if( this.view == "SCPage" ) {
		//this.pageDropDown.style.display = "none";
		this.croftImageP.style.display = "block";
	}

	this.view = "Listings";
	this.subItemId = id;
    this.locationDropDown.value = -1;
	this.GetListings( id );
	//get the ads
	this.GetAds( id );
	this.RestoreListings();
	this.locationTable.style.display = "inline";

};


// -----------------------------------------------------------------
HomePageManager.onListingClick = function( id )
{

  	//alert("onListingClick: "+ id  );
  	this.GetListingPage( id, 0 );

};

// -----------------------------------------------------------------
HomePageManager.onFind = function() {
   	var keyword = this.keywords.value.trim();
    if (keyword.length>0) {
  	    this.FindListings( keyword );
  	    if( this.view != "Map" ) {
		    this.RestoreListings();
	    }
    }
};

// -----------------------------------------------------------------
HomePageManager.onLocationChange = function()
{
  	if( this.locationDropDown.selectedIndex > 0 ) { //not "All Locations"
	   	var id = this.locationDropDown.options[ this.locationDropDown.selectedIndex].value;
  		//alert( id );
	  	this.GetListingsByLocation( id );
	} else {
     	this.GetListings( this.subItemId );
	}
	this.RestoreListings();

};

//--------------------------------------------------------------------
HomePageManager.GetMapTab = function( id ) {

	//alert( this.listingServer );
   	var response = core.xmlrpc.Call( this.listingServer, base.key, 'Listing.ViewMapTab', [id]);

	if (response instanceof XMLRPCFault)
	{
		base._handleFault(response);
	}
	else
	{

		var tabTD = document.getElementById( "PageTab");
		tabTD.innerHTML = response;

		//unselect old tab
		var tabTitle = document.getElementById( "PageTabTitle" + this.selectedTab );
		tabTitle.className= "TD_PageTabTitle";
		//select new one
		this.selectedTab = 4;
		tabTitle = document.getElementById( "PageTabTitle" + this.selectedTab );
		tabTitle.className= "TD_PageTabTitleSelected";

		var obj = new Object();
    	obj.listingServer = this.listingServer;
   		obj.mapServer = this.mapServer;
   		obj.pageId = id;

		MapManager.Init( obj );
	}
}

// -----------------------------------------------------------------
HomePageManager.onPageTabClick = function( page, tab )
{

  	//alert("onPageTabClick: page="+page + " tab =" + tab  );
  	if( tab == 4 ) { //map tab
  		this.GetMapTab( this.listingId );
	} else {
  		this.GetPageTab( page, tab );
	}

};

HomePageManager.AddToFavorites = function()
{
    var titleTD = document.getElementById("PageTitleTD");
    this.title = titleTD.innerText;
    var url = this.baseUrl + "?obj=Home&view=Business&id="+this.listingId;

    var ok = false;
    if(window.external && (!document.createTextNode || (typeof(window.external.AddFavorite)=='unknown'))) {
        try {
            window.external.AddFavorite(url, this.title );
            ok = true;
        }
        catch(e) {;}
    }

    if (!ok) {
        window.location.href = url;
        alert("Press and hold the 'Ctrl/Command' key and then press the 'D' key to bookmak this page.");
        document.title =  this.title;
    }

}