﻿/*
 *  Create the namespace
 */
ninemsn.mylocal.controls = function(){};

/*
 *  Create Constants
 */
ninemsn.mylocal.controls.CATEGORYLISTTYPE = 0;
ninemsn.mylocal.controls.SRATCHPADLISTTYPE = 1;
ninemsn.mylocal.controls.DEFAULTSRATCHPADLISTTYPE = 2;
ninemsn.mylocal.controls.RECENTLYSEARCHEDLISTTYPE = 3;
ninemsn.mylocal.controls.RECENTLYVIEWEDLISTTYPE = 4;
ninemsn.mylocal.controls.DEFAULTRECENTLYSEARCHEDLISTTYPE = 5;
ninemsn.mylocal.controls.DEFAULTRECENTLYVIEWEDLISTTYPE = 6;

/*
 *  List Control
 *
 *  Templates:
 *      Category List
 *      Scratch Pad
 */
function ListControl()
{
    /*
     *  Temoporary lists
     */
    var suburbListTMP = [
        { name : "Thornleigh", id : "" },
        { name : "Westleigh", id : "" },
        { name : "Cherrybrook", id : "" },
        { name : "Beecroft", id : "" },
        { name : "Cheltenham", id : "" },
        { name : "Normanhurst", id : "" },
        { name : "North Wahroonga", id : "" },
        { name : "Wahroonga", id : "" },
        { name : "West Pennant Hills", id : "" }
    ];
    var scratchPadTMP = [
        { name : "Foo in Bar", id : "" },
        { name : "Florists in Cooks Terrace", id : "" },
        { name : "Guitars in Stanleyville", id : "" },
        { name : "Bananas in Janices Place", id : "" },
        { name : "Pickled Eggs in Vinegar", id : "" }
    ];       
    var popularSearch = [
        { what : "Hairdressers", where : "Melbourne" },
        { what : "Florists", where : "Brisbane" },
        { what : "Bookstores", where : "Townsville" },
        { what : "Restaurants", where : "Melbourne" },
        { what : "Dentist", where : "Adelaide" },
        { what : "Plumber", where : "Hobart" },
        { what : "Medical Clinic", where : "Melbourne" },
        { what : "Employment", where : "Sydney" }
    ];    
    var popularViews = [
        { companyName : "Mount Gravatt Bookshop", recordId : "" }, 
        { companyName : "Quality Tanks Qld Pty Ltd", recordId : "" },
        { companyName : "Gray's Tanks", recordId : "" },
        { companyName : "Keim John R", recordId : "" },
        { companyName : "R & G Panel & Paint", recordId : "" },
        { companyName : "Silent Security Screens", recordId : "" },
        { companyName : "Andrew Barton", recordId : "" },
        { companyName : "Kallangur Physiotherapy & Sports Injury Clinic", recordId : "" }
    ];
    
    /*
     *  Private member variables.
     */
    var me = this;
    var _typeInf;
    var _response;    
    
    var types = [
        {   
            categoriesId :  "refine_categories_body",             
            catDataSource : window.g_categoryCollection, 
            subDataSource : window.g_surroundingSuburbs,
            suburbsId :     "refine_suburbs_body",
            renderFnc :     "renderRefinement", 
            suburbMin :     3, 
            suburbMax :     9,
            categoryMax :   6   
        },
        {   
            containerID :   "scratch_body", 
            renderFnc :     "renderScratchPad", 
            dataSource :    window.g_scratchPad,
            max :           9,
            defaultMSG :    "There are currently no items in your Scratch pad." 
        },
        {   
            containerID :   "scratch_body_main", 
            renderFnc :     "renderScratchPad", 
            dataSource :    window.g_scratchPad,
            max :           9,
            moreLink :      "View Scratch Pad",          
            defaultMSG :    "You currently have no items stored in your Scratch pad.<br/><br/>To add items to your Scratch pad, simply do a search and click on the 'Add to Scratch pad' link within the search results. The company will be added to your Scratch pad for future reference."
        },
        {
            containerID :   "searched_body", 
            renderFnc :     "renderDataBoundList", 
            title :         "Recent Searches",
            dataSource :    window.g_recentlySearched,
            activity :      "search",
            max :           9   ,
            defaultMSG :    "You currently have no recently searched items stored in your profile."
        },
        {
            containerID :   "viewed_body", 
            renderFnc :     "renderDataBoundList", 
            title :         "Recently Viewed",
            dataSource :    window.g_recentlyViewed,
            activity :      "view",
            max :           9,
            defaultMSG :    "You currently have no recently viewed items stored in your profile."
        },
        {
            containerID :   "viewed_body_main", 
            renderFnc :     "renderDataBoundList", 
            titleId :       "recently_viewed_title",
            title :         "Recently Viewed",
            dataSource :    window.g_recentlyViewed,
            altTitle :      "Popular Views", 
            altData :       popularViews,
            activity :      "view",
            max :           9,
            defaultMSG :    "You currently have no recently viewed items stored in your profile."
        },
        {
            containerID :   "search_body_main",             
            renderFnc :     "renderDataBoundList",
            titleId :       "recent_searches_title",
            title :         "Recent Searches",
            dataSource :    window.g_recentlySearched, 
            altTitle :      "Popular Searches",
            altData :       popularSearch,
            activity :      "search",
            max :           9,
            defaultMSG :    "You currently have no recently searched items stored in your profile."
        }
    ];
    
    /*
     *  Initialise
     *  Kicks off the rendering of a list control
     *  Requires the type to be passed in.
     */
    this.initialise = function(type)
    {
        /*
         *  Get the box info we need to create a box
         */
        if (utl.IsNullOrEmpty(type))
            return false;
            
        me._typeInf = types[type];
        
        /*
         *  If collections specified no need to make request
         */
        if (me._typeInf.dataSource)
        {
            me[me._typeInf.renderFnc](me._typeInf.dataSource); 
            return false;
        }
        
        /*
         *  Do our data retrieval.
         *  pass data retrieval a callback defined in the typeInf
         *  fire the render function from there
         */
         me.getData();
    };
    
    this.getData = function()
    {
        /*
         *  get our data using params set up in the type inf
         */
        
        /*
         *  nothing setup so call our callback directly
         */
        this.completeGetData();
    };
    
    this.completeGetData = function()
    {
        /*
         *  test response is valid
         */
         
        /*
         *  Call rendering function
         */
        me[me._typeInf.renderFnc](); 
    };
            
    this.renderRefinement = function()
    {
        try
        {
            me.renderCategories(me._typeInf.catDataSource, me._typeInf.categoriesId);
            me.renderSuburbs(me._typeInf.subDataSource);
            
            return false;
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderRefinement : {0}".format(ex.description));
        }   
        return false;
        
    };
    
    this.renderCategories = function(data, containerId)
    {
        try
        {
            var categoryContainer = document.getElementById(containerId);
            if (!categoryContainer || !data || data.length < 1)
                return false;
            
            /*
             *  We need to highlight the current category name
             *  If a category ID is not passed in the query string then
             *  Set the first category as the highlighted category
             */
            var paramCategoryId = ninemsn.mylocal.util.getQueryParam("categoryID");
            if (utl.IsNullOrEmpty(paramCategoryId))
                paramCategoryId = data[0].id;
            
            /*
             *  Clear out contents
             */ 
            categoryContainer.innerHTML = "";
                        
            /*
             *  Build list
             */
            var maxDisplayed = me._typeInf.categoryMax;
            if (maxDisplayed > data.length)
                maxDisplayed = data.length;
     
            var html = [];
            html.push("<div class=\"title\">Categories</div>");
            html.push("<ul>");
            for (var i = 0; i < maxDisplayed; i++)
            {
                if (paramCategoryId == data[i].id)
                {
                    html.push("<li>{0}</li>".format(data[i].name));
                    continue;
                }
                
                /*
                 *  Added a dependency to the ninemsn.mylocal.omniture library by referencing ninemsn.mylocal.omniture.EVENTREFINE
                 *  may need to abstract this later
                 */
                html.push("<li><a href=\"#\" onclick=\"omn.customActionHandler(omn.COOKIEINDEXREFINE);ninemsn.mylocal.search.navigateToPage('Search.aspx',null,null,null,{0},null); return false;\">{1}</a></li>".format(data[i].id, data[i].name));
            }
            html.push("</ul>");
            
            /*
             *  Insert into the dom
             */
            ninemsn.mylocal.util.insertAdjacentHTML(categoryContainer, "beforeend", html.join(''));
            
            return false;
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderCategories : {0}".format(ex.description));
        }   
        return false;
    };
    
    this.renderSuburbs = function(data, renderLess)
    {
        try
        {
            var suburbContainer = document.getElementById(me._typeInf.suburbsId);
            if (!suburbContainer || !data || data.length < 1)
                return false;
            
            /*
             *  Clear out contents
             */
            suburbContainer.innerHTML = "";  
                
            /*
             *  Build list
             */
            var maxDisplayed = me._typeInf.suburbMin;
            if (renderLess)
                maxDisplayed = me._typeInf.suburbMax;
                
            if (maxDisplayed > data.length)
                maxDisplayed = data.length;
     
            var html = [];
            html.push("<div id=\"refine_suburbs_title\" class=\"title\">Surrounding Suburbs</div>");
            html.push("<ul>");
            for (var i = 0; i < maxDisplayed; i++)
            {
                html.push("<li><a href='#' onclick=\"omn.customActionHandler(omn.COOKIEINDEXREFINE);ninemsn.mylocal.search.navigateToPage('Search.aspx',null,null,null,null,{0}); return false;\">{1}</a></li>".format(data[i].postcode, data[i].suburb));
            }
            html.push("</ul>");
            
            /*
             *  Insert into the dom
             */
            ninemsn.mylocal.util.insertAdjacentHTML(suburbContainer, "beforeend", html.join(''));
            
            /*
             *  Build more / less link
             */
            if (renderLess)
            {
                var less = document.createElement("a");
                less.href = "javascript:return false;";
                less.className = "link_left link_yellow";
                less.innerHTML = "less";
                ninemsn.mylocal.util.attachEventCallback(less,"onclick",me.renderSuburbs, data, false);
                suburbContainer.appendChild(less);
            }
            else
            {
                var more = document.createElement("a");
                more.href = "javascript:return false;";
                more.className = "link_left link_yellow";
                more.innerHTML = "more";
                ninemsn.mylocal.util.attachEventCallback(more,"onclick",me.renderSuburbs, data, true);
                suburbContainer.appendChild(more);
            }
            
            /*
             *  Insert into the dom
             */
            
            return false;
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderSuburbs : {0}".format(ex.description));
        }   
        return false;
    };
    
    this.renderScratchPad = function(data)
    {
        try
        {
            if (!me._response)
                me._response = data;
                
            /*
             *  Build default case
             */
             
            var sratchContainer = document.getElementById(me._typeInf.containerID);
            if (!sratchContainer)
                return false;
            
            /*
             *  Clear out contents
             */
            sratchContainer.innerHTML = ""; 
            
            /*
             *  If no data exists render the default state
             */
            if (!me._response || me._response.length < 1) 
            {
                sratchContainer.innerHTML = "<div class=\"refine_default\">{0}</div>".format(me._typeInf.defaultMSG);
                return false;
            }
            
            /*
             *  Build list
             */            
            var maxDisplayed = me._typeInf.max;
            if (maxDisplayed > me._response.length)
                maxDisplayed = me._response.length;
     
            var ul = document.createElement("ul");
            var maxLength = 40;
            for (var i = 0; i < maxDisplayed; i++)
            {
                var li = document.createElement("li");
                li.className = ((i % 2) > 0) ? "odd" : "";
                
                var companyName = me._response[i].companyName.length > maxLength ? me._response[i].companyName.substring(0,maxLength) + "..." : me._response[i].companyName
                
                var title   = li.appendChild(document.createElement('a'));
                title.href  = "javascript:return false;";
                title.className = "list_title";
                title.innerHTML = companyName;   
                utl.attachEventCallback(title, "onclick", ninemsn.mylocal.search.navigateToPage, 'Details.aspx', null, me._response[i].recordId);
                
                var kill    = li.appendChild(document.createElement('a'));
                kill.href   = "javascript:return false;";
                kill.className = "list_kill kill link_yellow";
                kill.innerHTML = "[x]";
                utl.attachEventCallback(kill, "onclick", me.deleteScratchPadEntry, i, me._response[i].recordId);
                
                ul.appendChild(li);
            }
            
            sratchContainer.appendChild(ul);
            
            var bottom = document.createElement("div");
            bottom.className = "panel_bottom_links";
            
            var more    = bottom.appendChild(document.createElement("a"));
            more.href   = "javascript:return false;";
            more.className = "link_left link_yellow";
            more.innerHTML = me._typeInf.moreLink ? me._typeInf.moreLink : "more";
            utl.attachEventCallback(more, "onclick", ninemsn.mylocal.search.navigateToPage, 'ScratchPad.aspx');
            
            
            var clearOptions = bottom.appendChild(document.createElement("div"));
            clearOptions.className = "link_right clear_options";
            
                var kill   = clearOptions.appendChild(document.createElement("a"));
                kill.href  = "javascript:return false;";
                kill.className = "link_right kill link_yellow";
                kill.innerHTML = "[x]";
                
                var clear   = clearOptions.appendChild(document.createElement("a"));
                clear.href  = "javascript:return false;";
                clear.className = "link_right link_yellow";
                clear.innerHTML = "clear all ";
            
            var clearFinalOptions = bottom.appendChild(document.createElement("div"));
            clearFinalOptions.className = "link_right clear_options";
            clearFinalOptions.style.display = "none";
            
                var text    = clearFinalOptions.appendChild(document.createElement("div"));
                text.className = "clear_options_title";
                text.innerText = "Are you sure?";
            
                var no          = clearFinalOptions.appendChild(document.createElement("a"));
                no.href         = "javascript:return false;";
                no.className    = "link_right link_yellow";
                no.innerHTML    = "no";
               
                var text    = clearFinalOptions.appendChild(document.createElement("span"));
                text.className = "link_right";
                text.innerHTML = "&nbsp;&nbsp;|&nbsp;&nbsp;";
                
                var yes         = clearFinalOptions.appendChild(document.createElement("a"));
                yes.href        = "javascript:return false;";
                yes.className   = "link_right link_yellow";
                yes.innerHTML   = "yes";
                            
                utl.attachEventCallback(kill, "onclick", function() { clearOptions.style.display = "none"; clearFinalOptions.style.display = "block"; return false; });
                utl.attachEventCallback(clear, "onclick", function() { clearOptions.style.display = "none"; clearFinalOptions.style.display = "block"; return false; });
                utl.attachEventCallback(no, "onclick", function() { clearOptions.style.display = "block"; clearFinalOptions.style.display = "none"; return false; }, true);
                utl.attachEventCallback(yes, "onclick", me.clearAllFromScratchPad);
                                           
            sratchContainer.appendChild(bottom);
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderScratchPad : {0}".format(ex.description));
        }   
        return false;
    };
    
    this.clearAllFromScratchPad = function()
    {
        try
        {
            /*
             *  Clear out the scratch pad
             */
            me._response = [];
            me[me._typeInf.renderFnc]();
            
            /*
             *  Persist modification
             */
            Ninemsn.MyLocalMigration.Proxies.Proxy.DeleteScratchPadByPUIDHash(utl.getPUIDHash());
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.clearAllFromScratchPad : {0}".format(ex.description));
        }   
        return false;
    };
    
    this.addScratchPadEntry = function(id)
    {
        try
        {   
            if (utl.IsNullOrEmpty(id))
                return false;

            var companyName = window.g_companyName;    
            if (utl.IsNullOrEmpty(companyName))
            {
                var elCompany = document.getElementById('company_' + id);
                if (!elCompany || !elCompany.innerHTML)
                    return false;    
                
                companyName = elCompany.innerHTML;
            }
            
            /*
             *  Check if the entry already exists
             *  If so return.
             */
            if (me._response && me._response.length > 0)
            {
                for (var i = 0; i < me._response.length; i++)
                {
                    var existingid = me._response[i].recordId;
                    if (existingid && existingid == id)
                        return false;
                }
            }   
        
            /*
             *  Add the entry
             *  and update the UI independantly
             */
            if (!me._response)
                me._response = [];
                
            me._response.splice(0,0,{ 'companyName' : companyName, 'recordId' : id });
            me[me._typeInf.renderFnc]();
            
            /*
             *  Update profile
             */
            Ninemsn.MyLocalMigration.Proxies.Proxy.InsertItemIntoScratchPad(utl.getPUIDHash(), id, companyName);
             
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.addScratchPadEntry : {0}".format(ex.description));
        }   
        return false;
    };
    
    this.deleteScratchPadEntry = function(index, recordId)
    {
        try
        {
            if (utl.IsNullOrEmpty(index) || !me._response || me._response.length < 1)
                return false;
                
            /*
             *  Delete the entry
             *  and update the UI independantly
             */
            me._response.splice(index,1);
            me[me._typeInf.renderFnc](); 
            
            /*
             *  Update profile
             */
            Ninemsn.MyLocalMigration.Proxies.Proxy.DeleteScratchPadByPUIDHashCompanyID(utl.getPUIDHash(), recordId);
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.deleteScratchPadEntry : {0}".format(ex.description));
        }   
        return false;
    };
   
    this.renderDataBoundList = function(data)
    {
        try
        {
            /*
             *  Build default case
             */
            var container = document.getElementById(me._typeInf.containerID);
            if (!container)
                return false;
            
            /*
             *  Clear out contents
             */
            container.innerHTML = "";
                                    
            /*
             *  If a title and title id are specified then set the title dynamically
             */
            var title; 
            if (me._typeInf.title && me._typeInf.titleId)
            {
                title = document.getElementById(me._typeInf.titleId);
                title.innerHTML = me._typeInf.title;
            }    
            
            /*
             *  If alternate info is specified AND data object does not exist, then render the from the alternate data source & title
             *  This occurs when the user loads the page, and there is no collections rendered in page.
             */
            if (!data && me._typeInf.altData)
            {
                title.innerHTML = me._typeInf.altTitle;
                data = me._typeInf.altData;
                me._typeInf.hideOptions = true
            }           
            
            /*
             *  If there is still no data then render the default state msg
             */
            if (!data ||  data.length < 1) 
            {
                container.innerHTML = "<div class=\"refine_default\">{0}</div>".format(me._typeInf.defaultMSG);
                return false;
            }
            me._response = data;
                        
            
            /*
             *  Build list
             */            
            var maxDisplayed = me._typeInf.max;
            if (maxDisplayed > data.length)
                maxDisplayed = data.length;
     
            var ul = document.createElement("ul");

            for (var i = 0; i < maxDisplayed; i++)
            {
                var li = document.createElement("li");
                li.className = ((i % 2) > 0) ? "odd" : "";
                
                var title   = li.appendChild(document.createElement('a'));
                title.href  = "javascript:return false;";
                title.className = "list_title";                                             
                                
                switch (me._typeInf.activity)
                {
                    case "search":
                        var what = data[i].what.toProperCase();
                        var where = data[i].where.toProperCase().stateToUpper();         
                        utl.attachEventCallback(title, "onclick", ninemsn.mylocal.search.getBusinessListings, what, where, data[i].type);
                        title.innerHTML = "{0} in {1}".format(what, where);
                        break;
                    case "view":
                        utl.attachEventCallback(title, "onclick", ninemsn.mylocal.search.navigateToPage, 'Details.aspx', null, data[i].recordId);
                        title.innerHTML = data[i].companyName;
                        break;
                    default:
                        utl.attachEventCallback(title, "onclick", ninemsn.mylocal.search.navigateToPage, 'Details.aspx', null, data[i].recordId);
                        title.innerHTML = data[i].companyName;
                        break;
                }
                                
                ul.appendChild(li);
            }
            
            container.appendChild(ul);
            
            if (me._typeInf.hideOptions)
                return false;
            
            var bottom = document.createElement("div");
            bottom.className = "panel_bottom_links";         
            
            var clearOptions = bottom.appendChild(document.createElement("div"));
            clearOptions.className = "link_right clear_options";
            
                var kill   = clearOptions.appendChild(document.createElement("a"));
                kill.href  = "javascript:return false;";
                kill.className = "link_right kill link_yellow";
                kill.innerHTML = "[x]";
                
                var clear   = clearOptions.appendChild(document.createElement("a"));
                clear.href  = "javascript:return false;";
                clear.className = "link_right link_yellow";
                clear.innerHTML = "clear all ";
            
            var clearFinalOptions = bottom.appendChild(document.createElement("div"));
            clearFinalOptions.className = "link_right clear_options";
            clearFinalOptions.style.display = "none";
            
                var text        = clearFinalOptions.appendChild(document.createElement("div"));
                text.className  = "clear_options_title";
                text.innerText  = "Are you sure?";
            
                var no          = clearFinalOptions.appendChild(document.createElement("a"));
                no.href         = "javascript:return false;";
                no.className    = "link_right link_yellow";
                no.innerHTML    = "no";
               
                var text        = clearFinalOptions.appendChild(document.createElement("span"));
                text.className  = "link_right";
                text.innerHTML  = "&nbsp;&nbsp;|&nbsp;&nbsp;";
                
                var yes         = clearFinalOptions.appendChild(document.createElement("a"));
                yes.href        = "javascript:return false;";
                yes.className   = "link_right link_yellow";
                yes.innerHTML   = "yes";
                            
                utl.attachEventCallback(kill, "onclick", function() { clearOptions.style.display = "none"; clearFinalOptions.style.display = "block"; return false; });
                utl.attachEventCallback(clear, "onclick", function() { clearOptions.style.display = "none"; clearFinalOptions.style.display = "block"; return false; });
                utl.attachEventCallback(no, "onclick", function() { clearOptions.style.display = "block"; clearFinalOptions.style.display = "none"; return false; }, true);
                utl.attachEventCallback(yes, "onclick", me.clearAllFromContainer);
            
            container.appendChild(bottom);
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderDataBoundList : {0}".format(ex.description));
        }   
        return false;
    };
    
    
    this.setLocationCase = function(where)
    {
        var returnVal = where;
        
        try
        {
            returnVal = where.replace(/\b(nsw|sa|qld|vic|nt|wa|act|tas)\b/g, function($1) { return $1.toUpperCase(); });
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.setLocationCase : {0}".format(ex.description));
        }
        
        return returnVal;
    };
    
    this.clearAllFromContainer = function()
    {
        try
        {
            /*
             *  Clear out the scratch pad
             */
            me._response = [];
            me[me._typeInf.renderFnc]();
            
            /*
             *  Persist modification
             */
            Ninemsn.MyLocalMigration.Proxies.Proxy.DeleteProfileActivityByProfileIDInfoType(utl.getPUIDHash(), me._typeInf.activity);
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.clearAllFromContainer : {0}".format(ex.description));
        }   
        return false;
    };      
}

/*
 *  Tab Control
 */
function TabControl()
{
    /*
     *  Private member variables
     */
    var me = this;
    var _typeInf;
    var selectedClass = "tab_header on";
    var unSelectedClass = "tab_header off";
    var types = [
        {   
            id :        "recently_viewed",
            headerId :  "recently_viewed_header",
            tabs :      [ 
                            { tabId : "search_header_main", bodyId : "search_body_main", headClass : "searched_selected" },
                            { tabId : "viewed_header_main", bodyId : "viewed_body_main", headClass : "viewed_selected" }
                        ]
        }
    ]; 
    
    this.initialise = function(type)
    {
        if (utl.IsNullOrEmpty(type))
            return false;
        
        /*
         *  Setup tab type
         */
        me._typeInf = types[type];
    };  
    
    this.handleTabClick = function(id)
    {
        try
        {
            if (utl.IsNullOrEmpty(id))
                return false;
                
            var header = document.getElementById(me._typeInf.headerId);   
                
            for (var i = 0; i < me._typeInf.tabs.length; i++)
            {
                var tabInf = me._typeInf.tabs[i];
                var tab = document.getElementById(tabInf.tabId);
                var body = document.getElementById(tabInf.bodyId);
                if (!tab || !body)
                    continue;
                    
                /*
                 *  Highlight tab, display body
                 */
                if (tabInf.tabId == me._typeInf.tabs[id].tabId)
                {
                    tab.className = selectedClass;
                    body.style.display = "inline";
                    header.className = tabInf.headClass; 
                    continue;
                }
                
                /*
                 *  Render regular tab, hide body
                 */
                tab.className = unSelectedClass;
                body.style.display = "none";
            }
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.handleTabClick : {0}".format(ex.description));
        }
        return false;
    };        
}

/* Ratings Control */
function RatingsControl()
{
    /*
     *  Private member variables
     */
    var me = this;
    this.elParent;
    this.starArray = [];
    this.mouseTimeout;
    
    this.initialise = function(parentId)
    {
        this.elParent = document.getElementById(parentId);
        if (!this.elParent)
            return false;
        
        this.renderStars();            
    }; 
    
    this.renderStars = function(id)
    {
        try
        {
            /*
             *  If the stars have no been created then create them
             */
            for (var i = 0; i < 10; i++)
            {            
                var classSide = i % 2 == 0 ? "left" : "right";
                var star = document.createElement('div');
                star.className = "star_" + classSide;
                me.elParent.appendChild(star);
                
                utl.attachEventCallback(star, "onclick", me.handleStarClick, (i + 1));
                utl.attachEventCallback(star, "onmouseover", me.handleStarMouseOver, i);
                utl.attachEventCallback(star, "onmouseout", me.handleStarMouseOut);
                
                me.starArray.push({ id : i, el : star});
            }
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.renderStars : {0}".format(ex.description));
        }
        
        return false;
    };
            
    this.highlightStars = function(id)
    {
        try
        {
            /*
             *  If the star array exists update the classes
             */
            for (var i = 0; i < 10; i++)
            {   
                var classSide = i % 2 == 0 ? "left" : "right";
                var star = me.starArray[i];
                if (i <= id)
                    star.el.className = "star_" + classSide + " hover";
                else    
                    star.el.className = "star_" + classSide;
            }
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.highlightStars : {0}".format(ex.description));
        }
        
        return false;
    };
     
    this.clearStars = function(id)
    {
        try
        {         
            /*
             *  If no id is passed then clear all the highlighted stars
             */
            for (var i = 0; i < 10; i++)
            {            
                var classSide = i % 2 == 0 ? "left" : "right";
                var star = me.starArray[i];
                star.el.className = "star_" + classSide;
            }
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.clearStars : {0}".format(ex.description));
        }
        
        return false;
    };
    
    this.handleStarMouseOut = function()
    {
        try
        {
            /*
             *  Create a timeout so we dont accidentally hide the selected stars when 
             *  navigating around the stars and mouseout continually fires
             */
            me.mouseTimeout = setTimeout(me.clearStars,10);
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.handleStarMouseOut : {0}".format(ex.description));
        }
        
        return false;
    };
    
    this.handleStarMouseOver = function(id)
    {
        try
        {
            /*
             *  Clear this timeout so we dont hide the selected stars
             */
            if (me.mouseTimeout)
            {
                clearTimeout(me.mouseTimeout);
                me.mouseTimeout = null;
            }
            
            me.highlightStars(id)
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.handleStarMouseOver : {0}".format(ex.description));
        }
        
        return false;
    };        
    
    this.handleStarClick = function(id)
    {
        try
        {
            var rating;
            rating = id / 2;
            
            var companyId = utl.getQueryParam("companyid");
            if (utl.IsNullOrEmpty(companyId))
                return false;
            
            /*
             *  Insert rating into DB
             */
            Ninemsn.MyLocalMigration.Proxies.Proxy.InsertCompanyRating(utl.getPUIDHash(), rating, companyId, me.ratingInsertSuccess, me.ratingInsertError);
            
            
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.handleStarClick : {0}".format(ex.description));
        }
        
        return false;
    };     

    this.ratingInsertSuccess = function(response)
    {
        try
        {
            if (!response || !response.length || utl.IsNullOrEmpty(response[0].toString()))
                return false;
            
            var rating = response[0];
            var rated = response[1];
            var ratedText = rated > 1 ? "ratings" : "rating";
             
            /*
             *  Calculate the new rating to display
             */ 
            rating = (Math.round(rating * 2) / 2).toString();
            if (rating.length == 1 && rating != '0')
                rating += ".0"; 
            
            rating = rating.replace(".","_");    

            /*
             *  Update the content to reflect the rating
             */                                    
            var avgRating = document.getElementById('average_rating');
            if (!avgRating)
                return false;                

            avgRating.className = "average_rating rating_{0}".format(rating);
            avgRating.innerHTML = "<div class=\"rated\">{0}&nbsp;{1}</div>".format(rated, ratedText);  
                        
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** this.handleStarClick : {0}".format(ex.description));
        }
        
        /*
         *  Hide ratings
         *  Do this outside the try catch so it always gets hidden after a rating           
         */
        var container = document.getElementById('ratings_container');
        if (!container)
           return false;
        container.style.display = "none";   
        
        return false;
    };
    
    this.ratingInsertError = function(response)
    {
        utl.debout("** RESPONSE ERROR ** this.ratingInsertError : {0}".format(response));
    }
}
