﻿//-------------------------------------------------------------------------------------------------
//  Utility for general methods
//-------------------------------------------------------------------------------------------------

var utility =
{
    // Gets the name of funtion fn.  Returns "none" if the function has no name.
    GetFunctionName: function(fn)
    {
        var name = /\W*function\s+([\w\$]+)\(/.exec(fn);

        if (!name)
            return 'none';

        return name[1];
    },

    // Returns an array of regex-captures (each an array in itself) of all matches of the specified regex on the 
    // specified input string.
    // param "regex": The regex to run on the input string
    // param "input": The input string to run the regex on.
    MatchAll: function(regex, input)
    {
        var results = [];

        while ((match = regex.exec(input)) != null)
        {
            results.push(match);
        }

        return results;
    },

    // Remove leading and trailing spaces from the string
    TrimString: function(input)
    {
        return input.replace(/^\s*(.*?)\s*$/, '$1');
    },

    // Toggle all checkboxes whose name contains the specified name
    // param "checkbox": The checkbox whose checked value should be used to determine whether to check or uncheck the other checkboxes
    // param "name": The name that, if contained in a checkbox input, means it should be toggled.
    ToggleCheckboxes: function(checkbox, name)
    {
        var isChecked = checkbox.checked;
        var form = document.forms[0];

        for (i = 0; i < form.length; i++)
        {
            if (form[i] != undefined)
            {
                if (form[i].name.indexOf(name) != -1)
                {
                    form[i].checked = isChecked;
                }
            }
        }
    },

    // Returns the selected DOM radio button object in the specified radio-group, or null if no radio button is selected
    GetSelectedRadio: function(radioGroup)
    {
        if (radioGroup[0])
        {
            // if the button group is an array (one button is not an array)
            for (var i = 0; i < radioGroup.length; i++)
            {
                if (radioGroup[i].checked)
                    return radioGroup[i];
            }
        }

        // if we get to this point, no radio button is selected
        return null;
    },

    //turns the first letter of a string to uppercase
    CapitalizeFirstLetter: function(wordString)
    {
        var result = wordString;
        if (wordString.length > 0)
        {
            var firstLetter = wordString.substr(0, 1).toUpperCase();
            var restOfString = wordString.substr(1);
            result = firstLetter + restOfString;

        }
        return result;
    },

    //copy text to clipboard (works for ie only)
    CopyToClipboard: function(text)
    {
        if (window.clipboardData && clipboardData.setData)
        {
            clipboardData.setData("Text", text);
        }
    },

    //replace all occurances of "toRpelace" is "text" with "replacewith"
    ReplaceAllOccurances: function(text, toReplace, replaceWith)
    {
        var resultValue = text;

        while (resultValue.indexOf(toReplace) != -1)
        {
            resultValue = resultValue.replace(toReplace, replaceWith);
        }
        return resultValue;
    },

    // param "arr" array: The array in which to search for a match
    // param "predicate" function: A function that a member of "arr" as its single argument and returns a boolean
    //      indicating whether or not it matches.
    FindMatch: function(arr, predicate)
    {
        for (var i in arr)
        {
            if (predicate(arr[i]))
                return arr[i];
        }

        return null;
    },

    ToggleElement: function(element)
    {
        if (element)
        {
            element.style.display = element.style.display == 'none' ? '' : 'none';
            return element.style.display;
        }
    },

    // Toggle an element's display
    // param "id": The id of the element whose display should be toggled;
    ToggleElementById: function(id)
    {
        return utility.ToggleElement(document.getElementById(id));
    },

    // Loops through form elements and executes "foreachFunc" on each element of type "type" containing "name" in its name
    ExecFuncOnElements: function(type, name, foreachFunc)
    {
        var form = document.forms[0];

        for (i = 0; i < form.length; i++)
        {
            if (form[i] != undefined && form[i].type == type)
            {
                if (form[i].name.indexOf(name) > -1)
                {
                    foreachFunc(form[i]);
                }
            }
        }
    },

    HideElement: function(id)
    {
        document.getElementById(id).style.display = 'none';
    },

    ShowElement: function(id)
    {
        document.getElementById(id).style.display = '';
    },

    // Looks for a member in the specified hashtable that is equal to the parameter o.
    // Returns the index of the found item if found, else returns -1.
    // param "arr": the array whose members to search
    // param "o": the object to search for in the array
    ArrayIndexOf: function(arr, o)
    {
        for (var i in arr)
        {
            if (arr[i] == o)
                return i;
        }

        return -1;
    },
    
    PrintHelpIFrame: function(frameClientId)
    {                
        document.frames[frameClientId].focus();
        document.frames[frameClientId].print();           
    }
    
};


//-------------------------------------------------------------------------------------------------
//  AjaxHelper
//-------------------------------------------------------------------------------------------------

var ajaxHelper =
{
    // The style of the div in which the progress image is contained
    wrapperStyle: 'text-align: center',

    // The progressImage control that will be displayed
    progressImage: '<div style="{0}"><img src="Images/progress.gif" /></div>',

    // progress image wrapped in a floating div (see relevant styles in koldin.css)
    floatingDiv: '<div id="centerpoint"><div id="dialog"><div style="{0}"><img src="Images/progress.gif" /></div></div></div>',
    methods: [],
    defaultContainerId: '',
    intervals: [],

    // Initialize a defaultContainerId for the progress image
    Init: function(defaultContainerId)
    {
        this.defaultContainerId = defaultContainerId;
        this.floatingDiv = this.floatingDiv.replace('{0}', this.progressImage);
    },

    // Shows the progress gif
    // param "method" (optional): Sets the key that the ajaxHelper will later use to hide the progress. This key should be the
    //      ajax-method name if the progress is for an ajax-call, because the FailedCallback method can thereby hide the progress
    //      gif if the method-call fails.
    //      If no method is passed, the progress gif will be displayed in a centered, floating div.
    // param "containerId" (optional): The id of the dom element in which to display the progress. If a method parameter
    //      is passed in and no containerId is passed, the ajaxHelper's defaultContainerId must be set, otherwise this method will
    //      do nothing.
    // param "wrapperStyle" (optional): Optional styling to apply to the progress image instead of the default stylnig.
    ShowProgress: function(method, containerId, wrapperStyle)
    {
        // Get progressImage div style
        wrapperStyle = wrapperStyle !== undefined ? wrapperStyle : ajaxHelper.wrapperStyle;

        if (!method)
        {
            // No key was specified: Show the progress in a floating div
            $j('body').append(ajaxHelper.floatingDiv.replace('{0}', wrapperStyle));
            return;
        }

        if (containerId == undefined && ajaxHelper.defaultContainerId == '')
            return; // no container found: return

        // Get container
        container = document.getElementById(containerId !== undefined ? containerId : ajaxHelper.defaultContainerId);

        // Save container in array
        ajaxHelper.methods[method] = { container: container, html: container.innerHTML };

        container.innerHTML = ajaxHelper.progressImage.replace('{0}', wrapperStyle);
    },

    // Inserts the specified content into the dom object saved under the specified "method". If no content is specified,
    // returns the original content (that was there when ShowProgress was called) to the dom object.
    // If no method is specified or the ajaxHelper does not contain the specified method-key, looks for the floating progress
    // div and, if found, removes it.
    HideProgress: function(method, content)
    {
        if (!method || !ajaxHelper.methods[method])
        {
            // No key was specified: Try hiding floating progress div
            $centerpoint = $j('#centerpoint');

            if ($centerpoint.length > 0)
                $centerpoint.remove();

            return;
        }

        if (!content)
            content = ajaxHelper.methods[method].html;

        ajaxHelper.methods[method].container.innerHTML = content;

        // mimick removal of the method from the array
        ajaxHelper.methods[method] = undefined;
    },

    // A generic complete method that recieves a ResultContainer whose Target property matches the "method" parameter
    // passed to the ajaxHelper when the ShowProgress method was called, and whose Result property is the html to be inserted
    // into the target dom object.
    // param "result": The returned ResultContainer
    GetControl_Complete: function(result, callback)
    {
        if (result)
            ajaxHelper.HideProgress(result.Target, result.Result)
    },

    ShowError: function(args)
    {
        alert("ארעה תקלה במהלך הפעולה האחרונה, אנא נסה שנית!");
        //alert("ארעה תקלה במהלך הפעולה האחרונה.  השגיעה: " + args);
    },

    // Begin polling for a result.
    // param "pollMethod": the delegated method to poll against.  This method should take no parameters and return a result.
    // param "interval": the interval between polls, in milliseconds.
    // param "onComplete": the delegated method to call when the poll method returns a result.  This method should take
    //           the result of the poll method as its only parameter and have no return value.
    BeginPolling: function(pollMethod, interval, onComplete)
    {
        // Get the name of the function to use as the key for the interval
        var name = utility.GetFunctionName(onComplete);

        //ajaxHelper.intervals[pollMethod] = window.setInterval('PollForResult("'+pollMethod+'", "'+onComplete+'")', interval)

        // Polls the server using the specified pollMethod per the specified interval, passing the pollMethod the specified
        // onComplete callback method.
        ajaxHelper.intervals[name] = window.setInterval(function() { pollMethod(onComplete); }, interval);
    },

    // Ends the polling process associated with the specified onComplete method.
    // param "onCompleteMethod": The method that was designated as the onComplete method when the ajaxHelper's BeginPolling method
    //      was called.
    StopPolling: function(onCompleteMethod)
    {
        window.clearInterval(ajaxHelper.intervals[utility.GetFunctionName(onCompleteMethod)]);
    }
};


//-------------------------------------------------------------------------------------------------
//  Events
//-------------------------------------------------------------------------------------------------

var eventMgr =
{
    msPageLoadCompleteEvent: 'msPageLoadComplete',
    onBeforeShowPopupEvent: 'onBeforeShowPopup',
    onAfterHidePopupEvent: 'onAfterHidePopup',
    handlers: {},

    // param "event" (string): The name of the event that should be handled by func
    // param "func" (function): The function to call when the registered-for event is raised. The function takes no parameters
    //      and does not have a return type.
    Register: function(event, func)
    {
        if (!eventMgr.handlers[event])
        {
            eventMgr.handlers[event] = [];
        }

        eventMgr.handlers[event].push(func);
    },

    // param "event" (string): The name of the event that should be raised. 
    //      All handler-functions registered for this event will be called.
    Raise: function(event)
    {
        var handlers = eventMgr.handlers[event];

        if (handlers)
        {
            for (var i in handlers)
            {
                handlers[i]();
            }
        }
    }
};


//-------------------------------------------------------------------------------------------------
//  Common Methods
//-------------------------------------------------------------------------------------------------

function FailedCallback(error, userContext, methodName)
{
    try{ajaxHelper.HideProgress(methodName, '');}
    catch(e){}
    ajaxHelper.ShowError(error);
    
    if(smartDropManager)
        if(smartDropManager.isWorking)
            smartDropManager.isWorking = false;
}

// Reset the current form
function ResetForm()
{	
	var form = document.forms[0];
    form.reset();
    
    for(var i=0; i < form.length; i++)
    {
		var element = form.elements[i];
		
        if(element.type == 'text')
            element.value = '';
        else if(element.type == 'select-one')
            form.elements[i].selectedIndex = 0;
    }
}

// utility function to find a specific querystring value
function GetQueryStringItem(itemName) 
{
    var queryString = window.location.search.substring(1);
    var itemArray= queryString.split("&");
    for (i=0;i<itemArray.length;i++) 
    {
        var nameValueItem = itemArray[i].split("=");
        if (nameValueItem[0].toLowerCase() == itemName.toLowerCase()) 
        {
            return nameValueItem[1];
        }
    }
 }
 
//function GetQuerystring(key, defaultValue)
//{
//    if (defaultValue == null) 
//        defaultValue = '';
//        
//    key = key.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
//    var regex = new RegExp('[\\?&]'+key+'=([^&#]*)');
//    
//    var qs = regex.exec(window.location.href);
//    
//    if(qs == null)
//        return defaultValue;
//    else
//        return qs[1];
//}
 
 
//Adds a css link dynamically to the page
function AddCssLink(cssName)
{
    var headID = document.getElementsByTagName("head")[0];         
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = 'Style/'+cssName+'.css';
//    cssNode.media = 'screen';
    headID.appendChild(cssNode);
}

//removes a css link dynamically from the page
function RemoveCssLink(cssName)
{
    var headID = document.getElementsByTagName("head")[0];         
    var cssLinks = headID.getElementsByTagName("link");      
    for( i in cssLinks)
    {
        if (cssLinks[i].href ==  'Style/'+cssName+'.css')
        {
            headID.removeChild(cssLinks[i]);
        }
    }
}

//-------------------------------------------------------------------------------------------------
//  Login
//-------------------------------------------------------------------------------------------------

var loginManager =
{
    popupId: '',
    nameLblId: '',
    ownerLoginRequired: false,

    divs: {
        beforeId: '',
        afterId: ''
    },

    panels: {
        login: { id: '', active: true },
        forgotPass: { id: '', active: false },
        ownerLogin: { id: '', active: false }
    },

    Init: function(popupId, nameLblId, beforeId, afterId, loginId, forgotPassId, ownerLoginPanelId, ownerLoginRequired)
    {
        this.popupId = popupId;
        this.nameLblId = nameLblId;
        this.divs.beforeId = beforeId;
        this.divs.afterId = afterId;
        this.panels.login.id = loginId;
        this.panels.forgotPass.id = forgotPassId;
        this.panels.ownerLogin.id = ownerLoginPanelId;
        this.ownerLoginRequired = ownerLoginRequired;

        eventMgr.Register(eventMgr.msPageLoadCompleteEvent, function()
        {
            if (loginManager.ownerLoginRequired)
            {
                loginManager.ShowPopup();
                loginManager.SwitchPanels('ownerLogin');
            }
        });
    },

    // Hide login popup
    HidePopup: function()
    {
        if (loginManager.popupId)
            $find(loginManager.popupId).hide();
    },

    // Show login popup
    ShowPopup: function()
    {
        if (loginManager.popupId)
        {
            $find(loginManager.popupId).show();
            document.getElementById('loginTxt').focus();
        }
    },

    // Switch between login div and forgotPass div
    SwitchPanels: function(panel)
    {
        for (var pnl in loginManager.panels)
        {
            if (pnl != panel)
            {
                loginManager.panels[pnl].active = false;
                utility.HideElement(loginManager.panels[pnl].id);
            }
        }

        loginManager.panels[panel].active = true;
        utility.ShowElement(loginManager.panels[panel].id);
    },

    // Show forgot password success message
    ShowForgotPassResult: function()
    {
        // Set label
        document.getElementById('emailLbl').innerHTML = document.getElementById("txtEmail").value;

        utility.HideElement('forgotPassDiv');
        utility.ShowElement('forgotPassResultDiv');
    },

    // Close forgotPass div if displayed, else close popup
    CloseCurrent: function()
    {
        // Clear status message
        loginManager.ShowStatusMessage('');

        if (loginManager.panels.login.active)
        {
            loginManager.HidePopup();
        }
        else if (loginManager.panels.ownerLogin.active)
        {
            // Closing the owner-login-panel means the user is cancelling his login: So log him out
            loginManager.LogoutUser();
            loginManager.HidePopup();
        }
        else
        {
            loginManager.SwitchPanels('login');
        }
    },

    // Display a message in the status label
    ShowStatusMessage: function(message)
    {
        document.getElementById('statusLbl').innerHTML = message;
    },

    LoginOwner: function()
    {
        var ownerName = document.getElementById('ownerNameTxt').value;

        if (ownerName == '')
        {
            alert("נא להקליד שם משתמש");
            return;
        }

        // clear status message
        loginManager.ShowStatusMessage('');

        AjaxService.ContentOwnerExists(ownerName, loginManager.CheckContentOwnerExists_Complete);
    },

    CheckContentOwnerExists_Complete: function(exists)
    {
        if (!exists)
        {
            if (!confirm('לא נמצא משתמש עם השם שהוקלד. האם ליצור משתמש חדש עבור שם זה?'))
                return;
        }

        AjaxService.LoginContentOwner(document.getElementById('ownerNameTxt').value, loginManager.LoginOwner_Complete);
    },

    LoginUser: function()
    {
        var username = document.getElementById("loginTxt").value;
        if (username.trim() == '')
        {
            alert("נא להקליד שם משתמש");
            return;
        }

        var password = document.getElementById("passwordTxt").value;
        if (password.trim() == "")
        {
            alert("נא להקליד סיסמה");
            return;
        }

        var doRememberPass = document.getElementById("rememberPassCheck").checked;

        // clear status message
        loginManager.ShowStatusMessage('');

        AjaxService.LoginUser(username, password, doRememberPass, loginManager.LoginUser_Complete);
    },

    LoginUser_Complete: function(args)
    {
        if (args.LoginSucceeded)
        {
            if (args.EndDate)
            {
                userNotifier.QueueExpiryMessage(args);
            }

            if (args.HasContentOwners)
            {
                loginManager.SwitchPanels('ownerLogin');
            }
            else
            {
                loginManager.LoginOwner_Complete(args);
            }
        }
        else
        {
            // Show recieved message
            loginManager.ShowStatusMessage(args.Message);
        }
    },

    LoginOwner_Complete: function(args)
    {
        //debugger;
        if (args.LoginSucceeded)
        {
            if (loginManager.popupId)
            {
                loginManager.HidePopup('popupId');
                utility.HideElement(loginManager.divs.beforeId);
                utility.ShowElement(loginManager.divs.afterId);
                document.getElementById(loginManager.nameLblId).innerHTML = args.Username;

                if (userNotifier.hasQueuedMessage)
                {
                    userNotifier.ShowExpiryMessage();
                }
                else
                {
                    window.location.reload();
                }
            }
            else
            {
                // There is no popup: Assume it is an iframe to login.aspx
                document.getElementById('loginDiv').style.display = 'none';
                window.parent.location.reload();
            }
        }
        else
        {
            // Show recieved message
            loginManager.ShowStatusMessage(args.Message);
        }
    },

    LogoutUser: function()
    {
        AjaxService.LogoutUser(loginManager.LogoutUser_Complete);
    },

    LogoutUser_Complete: function(args)
    {
        if (args)
        {
            if (loginManager.popupId)
            {
                document.getElementById(loginManager.nameLblId).innerHTML = '';
                utility.HideElement(loginManager.divs.afterId);
                utility.ShowElement(loginManager.divs.beforeId);
                window.location.href = window.location.href;
            }
            else
            {
                window.parent.location.reload();
            }
        }
        else
        {
            // Show error
            ajaxHelper.ShowError();
        }
    },

    SendPasswordToClient: function()
    {
        var email = document.getElementById("txtEmail").value;
        AjaxService.SendPasswordToClient(email, loginManager.SendPasswordToClient_Complete);
    },

    SendPasswordToClient_Complete: function(args)
    {
        if (args.Result == true)
            loginManager.ShowForgotPassResult();
        else if (args.Result == false && args.Info == false)
            loginManager.ShowStatusMessage('כתובת דואר אלקטרונית לא נמצאה');
        else
            ajaxHelper.ShowError('!ארעה תקלה בעת שליחת המייל , אנא נסה שנית');
    }
};


var userNotifier =
{
    expiryData: {},
    hasQueuedMessage: false,

    QueueExpiryMessage: function(data)
    {
        userNotifier.expiryData = data;
        userNotifier.hasQueuedMessage = true;
    },

    //Display expiry message
    ShowExpiryMessage: function(endDate, userName, company, clientId, email, daysLeft, hashavimProductCode)
    {
        if (arguments.length == 0 && userNotifier.hasQueuedMessage)
        {
            endDate = userNotifier.expiryData.EndDate;
            userName = userNotifier.expiryData.EncodedUserName;
            company = userNotifier.expiryData.UserCompany;
            clientId = userNotifier.expiryData.ClientId;
            email = userNotifier.expiryData.Email;
            daysLeft = userNotifier.expiryData.DaysLeft;
            hashavimProductCode = userNotifier.expiryData.HashavimProductCode;

            // clear the message data
            userNotifier.expiryData = {};
            userNotifier.hasQueuedMessage = false;
        }

        //var koldinProduct = "44";
        document.getElementById('endDateSpan').innerHTML = endDate;
        document.getElementById('daysleft').innerHTML = daysLeft;
        document.getElementById('contactLink').href =
                    "http://www.hashavim.co.il/productsinformation.aspx?val=6&expiring=true&userName=" + userName +
                        "&company=" + company + "&clientId=" + clientId + "&email=" + email +
                        "&prodId=" + hashavimProductCode + "&expiringOption=contactMe";

        document.getElementById('contactLinkMail').href =
                    "http://www.hashavim.co.il/productsinformation.aspx?val=6&expiring=true&userName=" + userName +
                        "&company=" + company + "&clientId=" + clientId + "&email=" + email +
                        "&prodId=" + hashavimProductCode + "&expiringOption=contactMail";

        $j("#canceledUser").hide();
        $j("#suspendedUser").hide();
        $j("#expiryWarning").show();
        $j("#expiryMessageDiv").show();

        document.getElementById('expiryMessageDiv').style.display = "inline";
    },

    //Hide expiry message
    HideExpiryMessage: function()
    {
        document.getElementById('expiryMessageDiv').style.display = "none";
        window.parent.location.reload();
    },

    // Display suspended user message
    ShowSuspendedUser: function(userName, company, clientId, email, hashavimProductCode)
    {
        //var koldinProduct = "44";
        document.getElementById('suspendContactLink').href =
                    "http://www.hashavim.co.il/productsinformation.aspx?val=6&expiring=true&userName=" + userName +
                        "&company=" + company + "&clientId=" + clientId + "&email=" + email +
                        "&prodId=" + hashavimProductCode + "&expiringOption=contactMe";

        $j("#canceledUser").hide();
        $j("#suspendedUser").show();
        $j("#expiryWarning").hide();
        $j("#expiryMessageDiv").show();
    },

    // Display canceled user message
    ShowCanceledUser: function(userName, company, clientId, email, hashavimProductCode)
    {
        //var koldinProduct = "44";
        document.getElementById('cancelContactLinkMail').href =
                    "http://www.hashavim.co.il/productsinformation.aspx?val=6&expiring=true&userName=" + userName +
                        "&company=" + company + "&clientId=" + clientId + "&email=" + email +
                        "&prodId=" + hashavimProductCode + "&expiringOption=contactMail";

        document.getElementById('cancelContactLink').href =
            "http://www.hashavim.co.il/productsinformation.aspx?val=6&expiring=true&userName=" + userName +
                "&company=" + company + "&clientId=" + clientId + "&email=" + email +
                "&prodId=" + hashavimProductCode + "&expiringOption=contactMe";

        $j("#canceledUser").show();
        $j("#suspendedUser").hide();
        $j("#expiryWarning").hide();
        $j("#expiryMessageDiv").show();
    }
};

//-------------------------------------------------------------------------------------------------
//  Tabbing
//-------------------------------------------------------------------------------------------------

// Controls tabbing in QuickSearchWUC, SearchHelp and MyAccount
var tabManager = 
{
    type: 'narrow',
    maagarHidId: '',
    
    tabs:[
        {tdId: 'tdPsika', divId: 'verdictsDiv',  isFirst: true, maagarId: 2},
        {tdId: 'tdHakika', divId: 'lawsDiv', isFirst: false, maagarId: 1},
        {tdId: 'tdAll', divId: 'combinedDiv', isFirst:false, maagarId: 0}
    ],
    
    currentMaagarId:
    {
        Get: function()
        {
            return document.getElementById(tabManager.maagarHidId).value;
        },
        Set: function(value)
        {
            document.getElementById(tabManager.maagarHidId).value = value;
        }
    },
    
    IsMaagarTabs: function()
    {
        return tabManager.maagarHidId != '' ? true : false;
    },
    
    classNames: {
        narrow:{
            active: 'tabNarrowActive',
            inactive: 'tabNarrowInactive',
            firstActive: 'tabNarrowFirstActive',
            firstInactive: 'tabNarrowFirstInactive'
        },
        wide:{
            active: 'tabWideActive',
            inactive: 'tabWideInactive',
            firstActive: 'tabWideFirstActive',
            firstInactive: 'tabWideFirstInactive'
        }
    }, 
    
    // optional params: if tabIds not passed, this method only sets current tab according to the maagarIdHid value.
    // param tabIds and divIds: 
    //      Clear current tabs array and add new set.  The first id in the array is set as the first tab (isFirst = true).
    //      Match parameter tabIds ids array with parameter divIds ids array.
    // param type: can be 'narrow' or 'wide', determines the width of the tabs pictures.
    Init: function(tabIds, divIds, type)
    {
        if(tabIds !== undefined)
        {
            // clear tabs array
            tabManager.tabs = [];
        
            // add new tabs
            for(i=0;i<tabIds.length;i++)
                tabManager.tabs.push({tdId: tabIds[i], divId: divIds[i], isFirst: (i==0 ? true : false)});
                
            // Set type
            tabManager.type = type;
        }
        else if(tabManager.IsMaagarTabs())
        {
            // Get current maagarId
            var maagarId = tabManager.currentMaagarId.Get();
            
            // Set tab according to current maagarId (in case user clicked back button)
            for(var i=0;i<tabManager.tabs.length;i++)
            {
                var tab = tabManager.tabs[i];
            
                if(tab.maagarId == maagarId)
                {
                    tabManager.ChangeTab(tab.tdId);
                    break;
                }
            }
        }
    },
    
    // param maagarHidId: send id of hidden to save currentMaagarId as the index of the current tab.  
    //      If not maagarTabs, send null.
    SetMaagarHid: function(maagarHidId)
    {
        if(maagarHidId != null && maagarHidId != '')
            tabManager.maagarHidId = maagarHidId;
    },
    
    // Select the requested tab (td) by its id and unselect all others.  Show matching div.
    ChangeTab: function(tdId)
    {
        var classNames = tabManager.classNames[tabManager.type];
    
        for(i=0;i<tabManager.tabs.length;i++)
        {
            var tab = tabManager.tabs[i]; 
            var td = document.getElementById(tab.tdId); // DOM td
            
            if(tab.tdId == tdId) // selected tab
            {
                td.className = (tab.isFirst ? classNames.firstActive : classNames.active);
                
                // Set right corner's class
                document.getElementById('tdRight').className = (tab.isFirst ? 'tabRightActive' : 'tabRight');
                    
                // show div
                document.getElementById(tab.divId).style.display = '';
                
                // set maagarId
                if(tabManager.IsMaagarTabs())
                    tabManager.currentMaagarId.Set(tab.maagarId);
            }
            else // other tab
            {
                td.className = (tab.isFirst ? classNames.firstInactive : classNames.inactive );
                
                document.getElementById(tab.divId).style.display = 'none'; //hide div
            }
        }
    }
};

// Controls tabbing in HomeQuickSearchWUC
var classicTabManager =
{
    tabs: [],
    maagarHidId: '',
    
    Init: function(maagarHidId)
    {
        this.maagarHidId = maagarHidId;
    
        this.AddTab('verdictSearchTab','verdictSearchTabDiv', 2);
        this.AddTab('lawSearchTab','lawSearchTabDiv', 1);
        this.AddTab('combinedSearchTab','combinedSearchTabDiv', 0);
    },
    
    currentMaagarId:
    {
        Get: function()
        {
            return document.getElementById(classicTabManager.maagarHidId).value;
        },
        Set: function(value)
        {
            document.getElementById(classicTabManager.maagarHidId).value = value;
        }
    },
    
    // Add a tab to the tab-array
    // param "tabId": id of tab.
    // param "divId": id of div associated with the tab.
    // param "className" (optional): a class-name to give the tab when it is not selected, or null.
    // param "hasIframe" (optional): true to hide the footer for this tab, else null.
    // param "maagarId": the maagar-ID of the tab.
    AddTab: function(tabId, divId, maagarId)
    {
        this.tabs.push({tabId: tabId, divId: divId, maagarId: maagarId});
    },
    
    SwitchTabs: function(aId)
    {
        // Get requested tab
        var a = document.getElementById(aId);
        a.className = 'selectedTab';
        
        for(i=0;i<this.tabs.length;i++)
        {
            var tab = this.tabs[i];
        
            if(tab.tabId == a.id) // selected tab
            {
                // show matching div
                document.getElementById(tab.divId).style.display = '';
                
                // Set tab's maagarId
                classicTabManager.currentMaagarId.Set(tab.maagarId);
            }
            else // not selected tab
            {
                document.getElementById(tab.tabId).className = 'inactiveTab'; // set back to default className
                document.getElementById(tab.divId).style.display = 'none'; // hide div
            }
        }
    }
};


//-------------------------------------------------------------------------------------------------
//  BrowserDetect
//-------------------------------------------------------------------------------------------------

/* Courtesy of http://www.quirksmode.org/js/detect.html */
var browserDetect = {
    initialized: false,
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
		this.initialized = true;
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};



