// *************************************************************
//  Service Directory Javascript
// *************************************************************
 

// *************************************
// Service Directory Client Context Data
// *************************************
// Applications
var SERVICES = "Services";
var USER = "User";
// Sub Applications
var FEEDBACK = "Feedback";
// Popup Mode
var NO_POPUP = "No";
var INSERT =  "Insert";
var EDIT = "Edit";
var REGISTER_USER_POPUP = "Register";
var CONFIRM_USER_POPUP = "Confirm";
var RESET_PASSWORD_POPUP = "Reset";

// List Paging
var LIST_PAGE = "Page";

var app = SERVICES;
var subApp = "";

var currentTextSearch = "";
var currentPage =0;
var contentWidth = 0;

var ServiceContentLoadingImage;


function InitServiceDirectory() {

    // Logon and logoff

    // *************************************
    // Startup Handlers - called from Master
    // *************************************


    onPageResize.subscribe(
        function(type, args) {
            SDAdjustContentLayout();
        }
    );

    onRefreshContent.subscribe(
        function(type, args) {
            SDRefreshContent();
        }
    );
    onRefreshNavigation.subscribe(
        function(type, args) {
            SD.NavigationTree.refresh();
        }
   );


}

// *************************************
// Event Handlers
// *************************************

// ---------------------------------------------------------
// Render a Bookmark at startup.
// Requires tree data to have been loaded.
// ---------------------------------------------------------
fnRenderBookmark = function (type, args) {
    try {
        SetContentToLocation(NNet.PageHistory.current());
    //    AddServicesHistory();
    } catch (e){logE("Service - fnRenderBookmark",e);}
}


function SDAdjustContentLayout() {
    try {
        var leftCol = $j("#leftColumn");
	    var rightCol = $j("#rightColumn");  
	    var main = $j("#main");
	    
        main.height(contentHeight);
        leftCol.height(contentHeight); 
	    // Adjust the hight of  tree etc nav's, as this appears to be the only way
        // of getting the multpage to the right height - otherwise it takes the full hieght
        // of the left div.
        //var navH = leftCol.innerHeight() - $j(sVars.SD_NavigationTabID).outerHeight();
        if (SD == null) var navH = leftCol.innerHeight();
        else var navH = leftCol.innerHeight() - SD.NavigationTabs.getHeaderHeight();
        $j("#TreePanel").height(navH);
        $j("#SMLContent").height(navH);
        // Splitter
        Splitter.height(contentHeight);
        // Rigth Column
        rightCol.height(contentHeight);

        rightCol.width(main.outerWidth()-SplitterWidth-leftColumnWidth);
        $j(sVars.SD_ContentToolBarPanelID).height(contentToolBarHeight);
        $j(sVars.SD_ContentPlaceholderPanelID).height(contentHeight-contentToolBarHeight);
       
	    AdjustView();
    } catch (e){logE("Service - SDAdjustContentLayout",e);}
}

function AdjustView(){
    try {
	    var serviceView = $j("#ServiceView");
	    var rightCol = $j("#rightColumn"); 
	    var svMap =  $j("#SVMap");

	    var cH = rightCol.outerHeight() - $j(sVars.SD_ContentToolBarPanelID).outerHeight();
        var cW = rightCol.outerWidth();
    
        contentWidth = cW;

        serviceView.width(cW);
        serviceView.height(cH);
        if (cW < 500) svMap.width(200);
        else if (cW > 500) svMap.width(250);

    } catch (e){logE("Service - AdjustView",e);}
}

// this is due to ie not scrolling  the map, firfox does.
function ScrollChanged(){
    try {
        var st = event.srcElement.scrollTop ;
        $j("#SVMap").css("top",-(st/10));
    } catch (e) {
        //logE("Service - ScrollChanged",e);
    }
}

// *****************************
// Other Called from Master Code
// *****************************

function SDRefreshContent() {
    try {
        try { // Button's may not be avaiable yet.
            SD.ContentToolBar.ListButton.hide();
            SD.ContentToolBar.MapButton.hide();
        } catch (e){}
        if (SD.ContentViewState == sVars.CATEGORY_CONTENT_VIEW_STATE) {
            CategorySearchServices(SD.CurrentCategoryType, SD.CurrentCategoryId, currentPage, SD.CurrentSearchSite);
        } else {
        if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) SD.DetailView.display(0,SD.CurrentServiceId, subApp == FEEDBACK);
            if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) TextSearchServices(currentTextSearch, currentPage, SD.CurrentSearchSite);
            else if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE)  CategorySearchServices(SD.CurrentCategoryType, SD.CurrentCategoryId, currentPage, SD.CurrentSearchSite);
            else if (SD.SearchSource == sVars.SERVICE_SEARCH_SOURCE)  ServiceSearchServices(SD.CurrentServiceId);
        }
    } catch (e){logE("Service - RefreshContent",e);}
}



// *****************************
// History Management Code
// *****************************



function SDApplicationHistoryChange(newLocation) {
    try {
        if (newLocation != "" ) SetContentToLocation(newLocation);
        else StartPage();
    } catch (e){logE("Service - ApplicationHistoryChange",e);}
}

function SetContentToLocation(location){
    try {
        var params=location.split("/");
        var popupMode = sVars.NO_POPUP;
        var popupConfig = {};
        currentPage = 0;
        if (  params[0] == SERVICES ) {
           app = SERVICES;
           if ( params[1] == sVars.DETAIL_CONTENT_VIEW_STATE ) {
                SD.ContentViewState=params[1];
                SD.CurrentServiceId=params[2]-0;
                if ( params[3] != undefined ) { // Detail page sub functions
                    if (params[3] == FEEDBACK) {
                        subApp = FEEDBACK;
                        if (params[4] != undefined) {
                            popupMode = params[4];
                            popupConfig.id = SD.CurrentServiceId; // could be service or listing id
                            if (popupMode == sVars.EDIT_POPUP) {
                                if (params[5] != undefined) popupConfig.feedbackId = params[5];
                                if (params[6] != undefined) popupConfig.user = params[6];
                            } else if (params[5] != undefined) popupConfig.user = params[6];
                        }
                    } else if (params[3] == sVars.EDIT_POPUP) {
                        popupMode = sVars.EDIT_POPUP
                        popupConfig.id = SD.CurrentServiceId; // could be service or listing id
                    }
                }
                SD.SearchSource = sVars.NO_SEARCH_SOURCE;
            } else { // List or map
                SD.ContentViewState=params[1];
                SD.SearchSource=params[2];
                if ( SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE ) {
                    SD.CurrentSearchSite=params[3]-0;
                    if ( params[4] == undefined ) SD.CurrentCategoryId = 0;
                    else {
                        SD.CurrentCategoryId=params[4]-0;
                        if ( params[5] != undefined ) {
                            if (params[5] == LIST_PAGE) currentPage = params[5] - 0;
                            else {
                                popupMode = params[5];
                                popupConfig.id = SD.CurrentCategoryId; 
                            }
                        }
                    }
                    if ( SD.CurrentCategoryId == 0 ) {
                        SD.CurrentCategoryType = sVars.SD_PAGE_CATEGORY_TYPE;
                        SD.CategoryPage.start();
                    } else {
                        SD.CurrentCategoryType = sVars.SD_CATEGORY_TYPE
                        //currentCatType = ShowTreeNode(SD.NavigationTree.Tree, currentCatId) - 0;
                        SD.NavigationTree.showTreeNode();                    
//                        if (SD.NavigationTree.Data != null) {
//                            var treeNodeData = SD.NavigationTree.Data.findNodeByValue(currentCatId);
//                            if (treeNodeData != null) {
//                                currentCatType = treeNodeData.C - 0;
//                                if (SD.NavigationTree.Tree != null) ShowTreeNode(SD.NavigationTree.Tree, currentCatId);
//                                else nnet.sd.onNavigationTreeRendered.subscribe(function(type, args) { ShowTreeNode(ServiceTree, currentCatId); });
//                            } else {
//                                currentCatId = 0;
//                                currentCatType = sVars.SD_PAGE_CATEGORY_TYPE;
//                                SD.CategoryPage.start();
//                            }
//                        } else {    // On startup if data has not been preloaded waits for async load.
//                            currentCatType = ShowTreeNode(SD.NavigationTree.Tree, currentCatId)-0;
////                            nnet.sd.onNavigationTreeDataReady.subscribe(
//                                function(type, args) {
//                                    var treeNodeData = SD.NavigationTree.Data.findNodeByValue(currentCatId);
//                                    currentCatType = treeNodeData.C - 0;
//                                    ShowTreeNode(SD.NavigationTree.Tree, currentCatId);
//                                }
//                            );
//                       }
                    }
                } else if (SD.SearchSource == sVars.SERVICE_SEARCH_SOURCE) {
                    if ( params[3] != undefined ) {
                        SD.CurrentServiceId = params[3]-0;
                    } else SD.CategoryPage.start();
                
                } else if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) {
                    SD.CurrentSearchSite=params[3]-0;
                    if ( params[3] != undefined ) currentPage=params[3]-0;
                    if ( params[4] != undefined ) {
                        currentTextSearch = unescape(params[4]);
                        var SearchText = $find(sVars.SearchTextID);  
                        SearchText.set_value(currentTextSearch);
                    }
                } else { // Probably no search - None
                    if (SD.CurrentCategoryType == sVars.SD_PAGE_CATEGORY_TYPE && SD.CurrentCategoryId == 0) SD.CategoryPage.start();
                }
            }
        } else if (  params[0] == USER ) {
            app=USER;
            if (params[1] != undefined) {
                popupMode = params[1];
                if (params[2] != undefined) popupConfig.user = params[2];
            }
        }
        ResetContent();

        if (popupMode != sVars.NO_POPUP) {
            popupConfig.view = SD.ContentViewState;
            popupConfig.loggedIn = NNet.CurrentUser.LoggedIn;
            popupConfig.func = subApp;
            ShowPopup(popupMode, popupConfig);
        }
    } catch (e){logE("Service - SetContentToLocation",e);}
}

function ShowPopup(popupMode, config){
    try {
        // Needs a delay as radWindowManager does not startup quick enough
        var user = config.user ? config.user : null;
        if (  app == SERVICES ) {
            if (config.view == sVars.LIST_CONTENT_VIEW_STATE && popupMode == sVars.INSERT_POPUP && config.id) new nnet.sd.Service().insert(config.id);
            else if (config.view == sVars.DETAIL_CONTENT_VIEW_STATE) {
                if (config.func == FEEDBACK && popupMode == sVars.INSERT_POPUP && config.id) {
                    if (config.loggedIn) new nnet.sd.Service().addFeedback(config.id);
                    else NNet.Security.showWithLogon('new nnet.sd.Service().addFeedback(' + config.id + ');', "Please Login or Signup before adding your Feedback", user);
                } else if (config.func == FEEDBACK && popupMode == sVars.EDIT_POPUP && config.feedbackId) {
                    if (config.loggedIn) new nnet.sd.Service().editFeedback(config.feedbackId );
                    else NNet.Security.showWithLogon('new nnet.sd.Service().editFeedback(' + config.feedbackId + ');', "Please Login before editing your Feedback", user);
                } else if (popupMode == sVars.EDIT_POPUP && config.id) {
                    if (config.loggedIn) new nnet.sd.Service().edit(config.id,0);
                    else NNet.Security.showWithLogon('new nnet.sd.Service().edit(' + config.id + ',0);', "Please Login before editing a Service", user);
                } else if (popupMode == sVars.RENEW_POPUP && config.id) {
                    if (config.loggedIn) new nnet.sd.Service().renew(config.id, 0);
                    else NNet.Security.showWithLogon('new nnet.sd.Service().renew(' + config.id + ',0);', "Please Login before renewing a listing", user);
                }
            }
        } else if (app == USER) {
            if (popupMode == sVars.CONFIRM_POPUP && config.user) new nnet.User({ id: config.user }).showRegConfirm();
            else if (popupMode == sVars.REGISTER_POPUP) NNet.CurrentUser.signUp();
            else if (popupMode == sVars.RESET_POPUP && config.user) new nnet.User({ id: config.user }).resetPassword();
        }
    } catch (e){logE("Service - ShowPopup",e);}
}



function ResetContent(){
    try {
        SDRefreshContent();
        //ServiceTree.unselectAllNodes();
        if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) SD.show(sVars.LIST_CONTENT_VIEW_STATE);
        else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) SD.show(sVars.MAP_CONTENT_VIEW_STATE);
        else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) SD.show(sVars.DETAIL_CONTENT_VIEW_STATE);
    } catch (e){logE("Service - ResetContent",e);}
}

function StartPage(){
    try {
        // Only do if not already start page, happens on start up when history changed to #
        if (SD.ContentViewState != sVars.CATEGORY_CONTENT_VIEW_STATE) {
            SD.ContentViewState = sVars.CATEGORY_CONTENT_VIEW_STATE;
            SD.CurrentCategoryType = sVars.SD_PAGE_CATEGORY_TYPE;
            SD.SearchSource = sVars.CATEGORY_SEARCH_SOURCE;
            SD.NavigationTree.Node = null;
            SD.CurrentCategoryId = 0;
            SD.CurrentListingId = 0;
            SD.CurrentServiceId = 0;
            currentTextSearch = "";
            currentPage = 0;
            SD.CurrentSearchSite = sVars.SD_SITE_SEARCH; // Should only be used to pass to server, not local comparisons as can contain a site id.
            SDRefreshContent();
        }
    } catch (e){logE("Service - StartPage",e);}
}

// *****************************
// Category Tree Handlers
// *****************************



 

// *****************************
// Site Context Handlers
// *****************************


function SetSiteContext(itemValue){
    try {
        SD.ContentToolBar.SiteDropdown.setValue(itemValue);
       // var SiteDropDown = $find(sVars.SiteDropDownID);  
       // var item = SiteDropDown.findItemByValue(itemValue);
       // if(item) item.select();
    } catch (e){logE("Service - SetSiteContext", e);}
}



// *****************************
// Get Data Methods
// *****************************
function ServiceSearchServices(serviceId){
    try {
        if ( SD.ContentViewState == sVars.CATEGORY_CONTENT_VIEW_STATE ) {
            SD.show(sVars.LIST_CONTENT_VIEW_STATE);
        }

        NNet.Page.setTitle()
        NNet.Page.setDescription()

        currentPage = 0;
        ServiceContentLoadingImage.show();
        document.body.style.cursor = 'wait';
	    if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) {
	        try { SD.ContentToolBar.MapButton.hide();} catch(e){}
            SDCallback.GetOneServiceList(serviceId, NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
	    } else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) {
	        try { SD.ContentToolBar.ListButton.hide(); } catch (e) { }
	        SD.NavigationTabs.disableMapTab();
	        SDCallback.GetOneServiceMap(serviceId, SD.MapView.callback, OnListCallbackError);
	    } else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) {
	        try { SD.ContentToolBar.MapButton.hide(); } catch (e) { }
            SDCallback.GetOneServiceList(serviceId,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
            try { SD.ContentToolBar.ListButton.hide(); } catch (e) { }
	        SD.NavigationTabs.disableMapTab();
	        SDCallback.GetOneServiceMap(serviceId, SD.MapView.callback, OnListCallbackError);
	    } 
    } catch (e){logE("Service - ServiceSearchServices", e);}
}

function CategorySearchServices(catType, catId, page, searchType){
    try {
        if (catType == sVars.SD_PAGE_CATEGORY_TYPE) SD.ContentViewState = sVars.CATEGORY_CONTENT_VIEW_STATE;
        else if (catType == sVars.SD_NEW_SERVICE_CATEGORY_TYPE) {
            SD.ServiceListing.get(catId, catType, searchType);
            return;
        } else if (catType == sVars.SD_USER_EDITED_SERVICE_CATEGORY_TYPE){
            SD.ServiceListing.get(catId, catType, searchType);
            return;
        } else if (catType == sVars.SD_USER_DELETED_SERVICE_CATEGORY_TYPE){
            SD.ServiceListing.get(catId, catType, searchType);
            return;
        } else if ( SD.ContentViewState == sVars.CATEGORY_CONTENT_VIEW_STATE ) {
            SD.show(sVars.LIST_CONTENT_VIEW_STATE);
        }

        NNet.Page.setTitle()
        NNet.Page.setDescription()
        
        currentPage = page;
        SD.CurrentSearchSite = searchType;
        //ServiceContentLoadingImage.show();
        document.body.style.cursor = 'wait';
	    if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) {
	        try { SD.ContentToolBar.MapButton.hide(); } catch (e) { }
            SDCallback.GetServiceListPages(catId, catType, page, searchType,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
//            SDCallback.GetServiceListPagesData(catId, catType, page, searchType,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
	    } else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) {
	        try {
	            SD.ContentToolBar.ListButton.hide(); 
	            SD.NavigationTabs.disableMapTab();
	        } catch (e) { }
	        SDCallback.GetServiceMap(catId, catType, searchType, SD.MapView.callback, OnListCallbackError);
	    } else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) {
	        try { SD.ContentToolBar.MapButton.hide(); } catch (e) { }
            SDCallback.GetServiceListPages(catId, catType, page, searchType,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
            try {
                SD.ContentToolBar.ListButton.hide(); 
	            SD.NavigationTabs.disableMapTab();
            } catch (e) { }
            SDCallback.GetServiceMap(catId, catType, searchType, SD.MapView.callback, OnListCallbackError);
	    }  else if (SD.ContentViewState == sVars.CATEGORY_CONTENT_VIEW_STATE) {
		    SDCallback.GetCategoryPages(SD.CurrentCategoryId,SD.CurrentCategoryType,currentPage,SD.CurrentSearchSite,NNet.ProcessID,GetCategoryPages_Callback,OnListCallbackError);
		    try { 
		        SD.ContentToolBar.MapButton.hide(); 
		        SD.ContentToolBar.ListButton.hide();
		        SD.NavigationTabs.disableMapTab();
	        } catch (e) { }
	    }
    } catch (e){logE("Service - CategorySearchServices", e);}
}

function TextSearchServices(searchText, page, searchType){
    try {
        if (searchText != '' ) {
            if ( SD.ContentViewState == sVars.CATEGORY_CONTENT_VIEW_STATE ) {
                SD.show(sVars.LIST_CONTENT_VIEW_STATE);
            }
            NNet.Page.setTitle()
            NNet.Page.setDescription()

            ServiceContentLoadingImage.show();
            document.body.style.cursor = 'wait';
            SD.CurrentSearchSite = searchType;
            currentPage = page;
            currentTextSearch=searchText;
            if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) {
                try { SD.ContentToolBar.MapButton.hide(); } catch (e) { }
                SDCallback.GetServiceListSearchPages(ParseSeachString(searchText), page, searchType,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
            } else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) {
                try { SD.ContentToolBar.ListButton.hide(); } catch (e) { }
                SD.NavigationTabs.disableMapTab();
                SDCallback.GetServiceMapSearch(ParseSeachString(searchText), searchType, SD.MapView.callback, OnListCallbackError);
            } else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) {
                try { SD.ContentToolBar.MapButton.hide(); } catch (e) { }
                SDCallback.GetServiceListSearchPages(ParseSeachString(searchText), page, searchType,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
                try { SD.ContentToolBar.ListButton.hide(); } catch (e) { }
	            SD.NavigationTabs.disableMapTab();
	            SDCallback.GetServiceMapSearch(ParseSeachString(searchText), searchType, SD.MapView.callback, OnListCallbackError);
	        }
	    } else alert("Please enter some text to search on when performing a search");
    } catch (e){logE("Service - TextSearchServices", e);}
}

function ParseSeachString( ss){
    ss = replaceCharacters(ss,"'",'~');
    ss = replaceCharacters(ss,'"',"'");
    return ss;
}

function replaceCharacters(origString,inChar,outChar) {
  var newString = origString.split(inChar);
  return newString.join(outChar);
}

function NewContentPage(page ){
    try {
        if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) TextSearchServices(currentTextSearch, page-1, SD.CurrentSearchSite);
        else if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE)  CategorySearchServices(SD.CurrentCategoryType, SD.CurrentCategoryId, page-1, SD.CurrentSearchSite);
        //AddServicesHistory();
    } catch (e){logE("Service - NewContentPage", e);}
}


function GetAdjacentSites(){
    try {
        if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) TextSearchServices(currentTextSearch, currentPage, sVars.SD_ADJACENT_SITE_SEARCH);
        else if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE)  CategorySearchServices(SD.CurrentCategoryType, SD.CurrentCategoryId, currentPage, sVars.SD_ADJACENT_SITE_SEARCH);
        SetSiteContext(sVars.SD_ADJACENT_SITE_SEARCH);
        //AddServicesHistory();
    } catch (e){logE("Service - GetAdjacentSites", e);}
}

function GetAllSites(){
    try {
        if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) TextSearchServices(currentTextSearch, currentPage, sVars.SD_ALL_SITE_SEARCH);
        else if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE)  CategorySearchServices(SD.CurrentCategoryType, SD.CurrentCategoryId, currentPage, sVars.SD_ALL_SITE_SEARCH);
        SetSiteContext(sVars.SD_ALL_SITE_SEARCH);
        //AddServicesHistory();
    } catch (e){logE("Service - GetAllSites", e);}
}


// *****************************
// Data Callbacks
// *****************************

function GetServiceListNew_Callback(Result) {
    try {
        var ServiceList = Result;
        CreateServiceListing(ServiceList);
    } catch (e) { logE("Service - GetServiceList_Callback", e); }
}



function CreateServiceListing(ServiceList) {
    try {
        var listingContainer = $j("#ListContainer");
        for (x = 0; x < ServiceList.Listings.length; x++) {
            var listing = ServiceList.Listings[x];
            var div=$j('<div>'+listing.Name+'</div>');
            div.appendTo(listingContainer);
        }
    } catch (e) { logE("Service - CreateServiceMap", e); }
}


function GetServiceList_Callback(Result){
    try {
        SD.NavigationTree.showTreeNode();
        if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) {
            ServiceContentLoadingImage.hide();
    	    document.body.style.cursor = 'default';
            if ( currentPage == 0 ) {   // Only bother to get map data for page 0, when paging map data will already be there.
                if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE) SDCallback.GetServiceMap(SD.CurrentCategoryId, SD.CurrentCategoryType, SD.CurrentSearchSite, SD.MapView.callback, OnListCallbackError);
                else if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) SDCallback.GetServiceMapSearch(ParseSeachString(currentTextSearch), SD.CurrentSearchSite, SD.MapView.callback, OnListCallbackError);
                else if (SD.SearchSource == sVars.SERVICE_SEARCH_SOURCE) SDCallback.GetOneServiceMap(SD.CurrentServiceId, SD.MapView.callback, OnListCallbackError);
            } else SD.ContentToolBar.showMapButton();
            NNet.PageHistory.add();
	    } else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) {
	        if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE) SD.NavigationTabs.enableMapTab();
	        else if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) SD.NavigationTabs.selectMapTab();
             ServiceContentLoadingImage.hide();
	        document.body.style.cursor = 'default'; 
	    } else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) {
             ServiceContentLoadingImage.hide();
   	        document.body.style.cursor = 'default';
   	        //if (SD.SearchSource == REFRESH_SEARCH) SD.show(sVars.LIST_CONTENT_VIEW_STATE);
   	        //if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE || SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE) SD.show(sVars.LIST_CONTENT_VIEW_STATE);
	    }
	    //$get("ListContainer").innerHTML = Result;
	    SD.ListingView.set(Result);
        GetServiceListJavascript();
        RunEmbeddedJS(Result);
        RefreshAd();
    } catch (e){logE("Service - GetServiceList_Callback", e);}
}


//function GetServiceMap_Callback(Result){
//    try {
//        var ServiceMap = Result;
//        CreateServiceMap(SD.MapView, ServiceMap);
//        if (SD.ContentViewState == sVars.LIST_CONTENT_VIEW_STATE) {
//            SD.ContentToolBar.showMapButton();
//	    } else if (SD.ContentViewState == sVars.MAP_CONTENT_VIEW_STATE) {
//	        SD.NavigationTabs.enableMapTab();
//	        SD.ContentToolBar.ListButton.show();
//             if (SD.SearchSource == sVars.CATEGORY_SEARCH_SOURCE) SDCallback.GetServiceList(SD.CurrentCategoryId, SD.CurrentCategoryType, SD.CurrentSearchSite,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
//             else if (SD.SearchSource == sVars.TEXT_SEARCH_SOURCE) SDCallback.GetServiceListSearch(ParseSeachString(currentTextSearch), SD.CurrentSearchSite,NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
//             else if (SD.SearchSource == sVars.SERVICE_SEARCH_SOURCE) SDCallback.GetOneServiceList(SD.CurrentServiceId, NNet.ProcessID, GetServiceList_Callback,OnListCallbackError);
//             NNet.PageHistory.add();
//	    } else if (SD.ContentViewState == sVars.DETAIL_CONTENT_VIEW_STATE) {
//	    }
//    } catch (e){logE("Service - GetServiceMap_Callback", e);}
//}

function GetCategoryPages_Callback(Result){
    try {
        SD.ContentViewState = sVars.CATEGORY_CONTENT_VIEW_STATE;
        SD.CategoryPage.display(Result);
        ServiceContentLoadingImage.hide();
        document.body.style.cursor = 'default'; 
        //RunEmbeddedJS(Result); not required as run by google maps on load into marker
        RefreshAd();
        NNet.PageHistory.add();
    } catch (e) { logE("Service - GetCategoryPages_Callback", e); }
}


//function ViewListing_Callback(Result){
//    try {
//        $j(sVars.SD_DetailContainerPanelID).empty()
//        $j(sVars.SD_DetailContainerPanelID).append(Result);
//        ShowDetail();
//        RunEmbeddedJS(Result);
//        ServiceContentLoadingImage.hide();
//        document.body.style.cursor = 'default';
//        NNet.PageHistory.add();
//    } catch (e){logE("Service - ViewListing_Callback", e);}
//}

//function ViewListingFeedback_Callback(Result){
//    try {
//        ViewListing_Callback(Result);
//        $j('#ServiceView').scrollTo('#FeedbackStart', 800);
//        NNet.PageHistory.add();
//    } catch (e){logE("Service - ViewListingFeedback_Callback", e);}
//}

function OnListCallbackError(Result) { 
    try {
         ServiceContentLoadingImage.hide();
	    document.body.style.cursor = 'default'; 
        alert("*** Error on Server when getting listing details:\r\n\r\n" + Result.message+"\r\n\r\nThis may be due to the Server being updated with a new version of the application") 
    } catch (e){logE("Service - OnListCallbackError", e);}
}

function RunEmbeddedJS(result){
    try {
       var start = result.indexOf('<script type="text/javascript">');
        if ( start != -1) eval(result.substring(start+31, result.indexOf('</script>')-1));
    } catch (e){logE("Service - RunEmbeddedJS", e);}
}

// *****************************
// Window Open Handlers
// *****************************

function NotOwner(){
    alert("Only the user owning this service can edit its details");
}

// *****************************
// Not Loggedin Handlers 
// *****************************
function fbLogin() {
    NNet.Security.showLogin('Please login to add feedback for a service listing');
}
function rvLogin() {
    NNet.Security.showLogin('Please login to add a Review to a service listing');
}
function edLogin() {
    NNet.Security.showLogin('Please login to edit a service listing');
}

function emLogin() {
    NNet.Security.showLogin('Please login to send mail from the site');
}

function login(msg) {
    NNet.Security.showLogin('Please login to add feedback for a service listing');
}


// *****************************
// List Page 
// *****************************

function GetServiceListJavascript(){
   if(NiftyCheck()){NFRounded('div.enhanced','top','transparent','#5987D6','border #8DB1E5 smooth');NFRounded('div.enhanced','bottom','transparent','#F0F0E7','small border #8DB1E5');}
}

// Display list popup map
function ViewMap(mapElm,lat,lng){
    try {
	    if (GBrowserIsCompatible()) {
            point = new GLatLng(lat, lng);
	        var map = new GMap2(mapElm);
            map.addControl(new GSmallMapControl());
	        map.addControl(new GMapTypeControl());
	        map.setCenter(point, 16);
	        marker = new GMarker(point);
            map.addOverlay(marker);
        }
    } catch (e){logE("Service - ViewMap", e);}
}


// Display list popup map
function DM(mapElm,lat,lng){
    try {
	    if (GBrowserIsCompatible()) {
            point = new GLatLng(lat, lng);
	        var map = new GMap2(mapElm);
            //map.addControl(new GSmallMapControl());
	        //map.addControl(new GMapTypeControl());
	        map.setCenter(point, 16);
	        marker = new GMarker(point);
            map.addOverlay(marker);
        }
    } catch (e){logE("Service - DM", e);}
}

// *****************************
// Listing Page 
// *****************************

function CreateServiceList(ServiceList){
    try {
      //$get("ListContainer").innerHTML  
        for (x=0; x < ServiceList.Listings.length; x++ ){
            var Listing = ServiceMap.Listings[x];
         }
        // Map Side bar stuff
        myNewtbody.appendChild(docFragment);
        mytable.replaceChild(myNewtbody, mytbody);     
     } catch (e){logE("Service - CreateServiceMap", e);}
}


// *****************************
// Map Page 
// *****************************


 function createMarker(point, sid,docF,gmap,lid, title,description,url,address,pictureURL,enhanced,loggedIn,email,isEditable,feedbackCount, ratingImage ) {
     try {
       // Google map stuff
        
       infoHTML = new Megasoft78.StringBuilderEx();
       infoHTML.appendFormatEx("<table class='MapEntry' width='?px' border='0' cellpadding='0' cellspacing='0'><tr>",(enhanced ? "350" : "250"));
       infoHTML.appendFormatEx("<td class='TitleRow'><span class='Title'><a href='#' onclick='SD.DetailView.display(?,?,false); return false;' >?</a></span>", lid, sid, title);
       infoHTML.append("<span class='Toolbar'><input title='Edit Listing Details' class='icon' src='http://img1.neighbournet.com/resource/icon/small/edit.gif' onclick='");
       if (loggedIn) { if (isEditable) infoHTML.appendFormatEx("new nnet.sd.Service().edit(?,?);", sid, lid); else infoHTML.append("NotOwner();") } else { infoHTML.append("edLogin();") } 
       infoHTML.append("return false;' type='image'>");
       if (url != null) infoHTML.appendFormatEx("<input title='Open Website in new window' class='icon' src='http://img1.neighbournet.com/resource/icon/small/website.gif' onclick='window.open(\"http://?\",\"?\");return false;' type='image'>", url, sid);
       if (email != null) infoHTML.appendFormatEx("<input type='image' title='Email contact for service' class='icon' src='http://img1.neighbournet.com/resource/icon/small/mail.gif' onclick=\"new nnet.sd.Service().email('?');return false;\" style='border-width:0px;' />", sid);
       infoHTML.appendFormatEx("<input id='Blowup?' title='See location of Service' class='icon' src='http://img1.neighbournet.com/resource/icon/small/map.gif' style='height: 17px;' type='image' onclick='return false;'  >", sid);
       infoHTML.append("</span></td></tr>");
       infoHTML.appendFormatEx("<tr><td class='AddressRow'><span class='Address'>?</span></td></tr>",address);
       infoHTML.appendFormatEx("<tr><td class='DescriptionRow'>?<span class='Description'>?</span></td></tr>",pictureURL,unescape(description));
       infoHTML.append("<tr><td class='FooterRow'><span class='Feedback'>");
       if (feedbackCount == 0) {
            infoHTML.append("<a href='#' onclick='");
            if (loggedIn) infoHTML.appendFormatEx("new nnet.sd.Service().addFeedback(?)", sid); else infoHTML.append("edLogin()");
            infoHTML.append(";return false;'>Add Feedback</a>");
       } else {
       infoHTML.appendFormatEx("<a href='#' onclick='SD.DetailView.display(?,?,true); return false;'>Feedback (?) ?</a>",lid, sid, feedbackCount, ratingImage);
       }
       infoHTML.append("</span></td></tr></table>");
       
       var infoHTMLString = infoHTML.toString();
       var marker = new GMarker(point,sid);
       
       GEvent.addListener(marker, "mouseover", function() {
            marker.openInfoWindowHtml(infoHTMLString);
            // show in side bar
            var smlt = document.getElementById('SMLT'+sid);
            smlt.className = "Selected Enhanced"+enhanced;
            // Marker events
            //var blowup = document.getElementById("Blowup" + sid);
            $j('#Blowup' + sid).click(function() { marker.showMapBlowup(opts = { zoomLevel: 17 }); });
            //if (blowup != null) blowup.onclick = function() { marker.showMapBlowup(opts = { zoomLevel: 17 }); }
        });
        GEvent.addListener(marker, "infowindowclose", function() {
            var smlt = document.getElementById('SMLT'+sid);
            smlt.className = "UnSelected Enhanced"+enhanced;
        });

        // Map Side bar stuff
        var trElem = document.createElement("tr");
        trElem.className = "SMLTrow";
        var tdElem = document.createElement("td");
        tdElem.setAttribute( 'id' , 'SMLT'+sid );
        tdElem.style.cursor = "pointer";
        tdElem.className = "Enhanced"+enhanced;
        var txtNode = document.createTextNode(title);
        tdElem.appendChild(txtNode);
        tdElem.onclick = function() {marker.showMapBlowup(opts={zoomLevel:17});}
        tdElem.onmouseover = function() {
            this.className = "Selected Enhanced" + enhanced;
            marker.openInfoWindowHtml(infoHTMLString);
            // Marker events
            var blowup = document.getElementById("Blowup" + sid);
            // try/catch as blowup is null sometimes.
            try { blowup.onclick = function() { marker.showMapBlowup(opts = { zoomLevel: 17 }); } } catch (e) { }
        }
        //tdElem.onmouseout =function() {gmap.closeInfoWindow();}
        tdElem.onmouseout =function() {
            this.className = "UnSelected Enhanced"+enhanced;
        }
        trElem.appendChild(tdElem);   
        docF.appendChild(trElem);
        return marker;
    } catch (e){logE("Service - createMarker", e);}
}

function createMarker2(point, lid,docF,gmap,sid, title,description,url,address,pictureURL,enhanced,loggedIn,email,isEditable ) {
    try {
        // Google map stuff
        var marker = new GMarker(point,sid);
        var infoHTML = "<div class='MapEntry Enhanced"+enhanced+"'><div class='TitleRow'><span class='Title'>"+
            (url == null ? title : "<a class='external' href='http://"+url+"' target='t"+sid+"'>"+title+"</a>")+
            "</span>"+
	        "<span class='Toolbar'>"+
	        "<input title='Edit Listing Details' class='icon' src='http://img1.neighbournet.com/resource/icon/small/edit.gif' onclick='" +
	        (loggedIn ? (isEditable ? "new nnet.sd.Service().edit(" + sid + "," + lid + ");" : "NotOwner();") : "edLogin();") +
	        "return false;' type='image'>"+
	        (url == null ? "" : "<input title='Open Website in new window' class='icon' src='http://img1.neighbournet.com/resource/icon/small/website.gif' onclick='window.open(\"http://" + url + "\",\"" + sid + "\");return false;' type='image'>") +
            (email == null ? "" : "<input type='image' title='Email contact for service' class='icon' src='http://img1.neighbournet.com/resource/icon/small/mail.gif' onclick=\"new nnet.sd.Service().email('" + sid + "');return false;\" style='border-width:0px;' />") +
            "<input id='Blowup" + sid + "' title='See location of Service' class='icon' src='http://img1.neighbournet.com/resource/icon/small/map.gif' style='height: 17px;' type='image'>" +
            "</span></div><div class='AddressRow'><span class='Address'>"+address+"</span></div>"+
            "<div class='DescriptionRow'>"+pictureURL+"<span class='Description'>"+description+"</span></div></div>";
        GEvent.addListener(marker, "mouseover", function() {
            marker.openInfoWindowHtml(infoHTML);
            // show in side bar
            var smlt = document.getElementById('SMLT'+sid);
            smlt.className = "Selected Enhanced"+enhanced;
            // Marker events
            var blowup = document.getElementById("Blowup"+sid);
            blowup.onclick = function() {marker.showMapBlowup(opts={zoomLevel:17});}
        });
        GEvent.addListener(marker, "infowindowclose", function() {
            var smlt = document.getElementById('SMLT'+sid);
            smlt.className = "UnSelected Enhanced"+enhanced;
        });

        // Map Side bar stuff
        var trElem = document.createElement("tr");
        trElem.className = "SMLTrow";
        var tdElem = document.createElement("td");
        tdElem.setAttribute( 'id' , 'SMLT'+sid );
        tdElem.style.cursor = "pointer";
        tdElem.className = "Enhanced"+enhanced;
        var txtNode = document.createTextNode(title);
        tdElem.appendChild(txtNode);
        tdElem.onclick = function() {marker.showMapBlowup(opts={zoomLevel:17});}
        tdElem.onmouseover = function() {
            this.className = "Selected Enhanced"+enhanced;
            marker.openInfoWindowHtml(infoHTML);
            // Marker events
            var blowup = document.getElementById("Blowup"+sid);
            blowup.onclick = function() {marker.showMapBlowup(opts={zoomLevel:17});}
        }
        //tdElem.onmouseout =function() {gmap.closeInfoWindow();}
        tdElem.onmouseout =function() {
            this.className = "UnSelected Enhanced"+enhanced;
        }
        trElem.appendChild(tdElem);   
        docF.appendChild(trElem);
        return marker;
    } catch (e){logE("Service - createMarker2", e);}
}
// ******************************
// Display Handlers
// ******************************
//function ShowList(){
//     try {
//       SD.ContentViewState = sVars.LIST_CONTENT_VIEW_STATE;
//        //xDisplay('CategoryContainer','none');
//        //xDisplay('MapContainer','none');
//        //xDisplay('DetailContainer','none')
//        //xDisplay('ListContainer','block')
//        
//        $j('#CategoryContainer').hide();
//        //$j('#ListContainer').show();
//        SD.ListingView.show();
//        $j(sVars.SD_DetailContainerPanelID).hide();
//        $j('#MapContainer').hide();
//       
//        
//        try { // May not yet be defined on first page display, will be hidden then anyway
//            SD.ContentToolBar.ListButton.hide();
//            SD.ContentToolBar.showMapButton();
//            SD.NavigationTabs.disableMapTab();
//        } catch(e){};
//    } catch (e){logE("Service - ShowList", e);}
//}

//function ShowDetail(){
//    try {
//        SD.ContentViewState = sVars.DETAIL_CONTENT_VIEW_STATE;
//        //xDisplay('CategoryContainer','none');
//       // xDisplay('MapContainer','none');
//       // xDisplay('ListContainer','none')
//        //xDisplay('DetailContainer','block')
//        
//        $j('#CategoryContainer').hide();
//        //$j('#ListContainer').hide();
//        SD.ListingView.hide();
//        $j(sVars.SD_DetailContainerPanelID).show();
//        $j('#MapContainer').hide();

//        if (SD.SearchSource != sVars.NO_SEARCH_SOURCE){ // Only display these wen detail is result of a search, not a link
//            try { // May not yet be defined on first page display, will be hidden then anyway
//                SD.ContentToolBar.ListButton.show();
//                SD.ContentToolBar.showMapButton();
//                SD.NavigationTabs.disableMapTab();
//            } catch(e){};
//        }
//        AdjustView();
//    } catch (e){logE("Service - ShowDetail", e);}
//}


function JavaScriptEval_Callback(Result){
    try {
        eval(Result);
    } catch (e){logE("Service - JavaScriptEval_Callback", e);}
}


//function DisplayReviews(){
//    $j('#ReviewPanel').show();
//    $j('#AddReview').show();
//    $j('#ShowReviews').hide();
//}

//function HideReviews(){
//    $j('#ReviewPanel').hide();
//    $j('#AddReview').hide();
//    $j('#ShowReviews').show();
//}

//function NoReviews(){
//    $j('#ReviewPanel').hide();
//    $j('#AddReview').show();
//    $j('#ShowReviews').hide();
//}


//function GoToFeedback(){
//    $j('#ServiceView').scrollTo('#FeedbackStart', 800);
//}


// *************************************
// Common Handlers - move into common script
// *************************************
 
function SDContentTBHide(){
    $j(sVars.SD_ContentPlaceholderPanelID).height(contentHeight);
}

function SDContentTBShow(){
    $j(sVars.SD_ContentToolBarPanelID).height(contentToolBarHeight);
    $j(sVars.SD_ContentPlaceholderPanelID).height(contentHeight-contentToolBarHeight);
}



