﻿var reEmpty = /^(.+)$/;
var regExNumbers = /^[+]?\d*$/;
var regExLetters = /^[\sA-Za-zא-ת]+$/;
//timeout interval in milliseconds between keyup event and checking for a new event
var INTER_KEY_INTERVAL = 500;

var smartDropManager =
{
    
    focusedId: '',
    dropsArray: [],
    masks: [],
    isWorking: false,
    selectionRequired: false,
    
    //current text in field
    currentText : '',
    
    //currently running Query ajax request (for the purpose of aborting it, when needed)
    currentAjaxRequest: null,
    
    // Hide all smartDrop divs
    HideDrops: function()
    {
        for (var id in this.dropsArray)
        {
            smartDropManager.HideDiv(id);
        }
    },

    HideDiv: function(divId)
    {
        if (smartDropManager.IsIE()) // Remove mask for IE
            smartDropManager.RemoveMask(divId);

        var div = document.getElementById(divId);

        if (div) // hide div
            div.className = "hide";
            
        if (!smartDropManager.selectionRequired )
        {
            $j("#"+this.dropsArray[divId]['dropImgId']).hide();
        }

    },

    // Add a smartDrop to the dropsArray
    // param "onValueChanged" (optional): A method to call when the value of the smart-drop changes
    AddDrop: function(divId, txtId, valueId, poolId, dropImgId, selectionRequired, onValueChanged)
    {
        this.dropsArray[divId] =
        {
            txtId: txtId,
            valueId: valueId,
            poolId: poolId,
            dropImgId: dropImgId,
            selectionRequired: selectionRequired,
            onValueChanged: onValueChanged
        };
        
        if (selectionRequired)
        {
           $j("#"+dropImgId).show();
        }
        else
        {
           $j("#"+dropImgId).hide();
        }
    },

    // Changes the poolType of the requested smartDrop.
    // param "divId": the client ID of the smartDrop's ListDiv whose poolType you want to change.
    ChangeDropPool: function(divId, poolType)
    {
        var hid = document.getElementById(this.dropsArray[divId].poolId);
        hid.value = poolType;
    },

    ShowDiv: function(div)
    {
        div.className = 'smartDrop_div_show';
        if (!smartDropManager.selectionRequired )
        {
            $j("#"+this.dropsArray[div.id]['dropImgId']).show();
        }

        if (smartDropManager.IsIE()) // Add mask for IE
            window.setTimeout('smartDropManager.SetMask("' + div.id + '")', 50);
    },

    // Sets the value of the hiddenId belonging to the smartDrop identified by the specified divId
    // param "divId": the client ID of the smartDrop whose value should be set.
    // param "value": the value to set to the smartDrop's hidden
    SetSmartDropValue: function(divId, value)
    {
        var smartDrop = this.dropsArray[divId];
        var hidden = document.getElementById(smartDrop.valueId);

        if (hidden.value != value)
        {
            hidden.value = value;

            // notify that the value has changed
            if (smartDrop.onValueChanged) smartDrop.onValueChanged(value);
        }
    },

    // Returns the value from the hiddenId belonging to the smartDrop identified by the specified divId
    // param "divId": the client ID of the smartDrop whose value to get.
    GetSmartDropValue: function(divId)
    {
        return document.getElementById(this.dropsArray[divId].valueId).value;
    },

    GetSmartDropText: function(divId)
    {
        return document.getElementById(this.dropsArray[divId].txtId).value;
    },

    SetSmartDropSelection: function(objectName, keyId, divId, doFocus)
    {
        var txt = document.getElementById(smartDropManager.dropsArray[divId].txtId);
        //txt.value = objectName;
        //replace the sub string "SingleGeresh" with "'"
        txt.value = objectName.replace(/SingleGeresh/g, "'");

        smartDropManager.SetSmartDropValue(divId, keyId);
        smartDropManager.HideDiv(divId);
    },

    SetSmartDropSelectionNoHide: function(objectName, keyId, divId, doFocus)
    {
        var txt = document.getElementById(this.dropsArray[divId].txtId);
        txt.value = objectName;

        smartDropManager.SetSmartDropValue(divId, keyId);
    },

    GetSmartDropListByLetters: function(text, divId, objectType, poolType)
    {
        text = text.replace(/'/g, "&apos;");
        smartDropManager.currentText = text;
        
        window.setTimeout("smartDropManager.PerformSmartDropListByLettersRequest('"+text+"', '"+divId+"', '"+objectType+"', '"+poolType+"')",INTER_KEY_INTERVAL) ;
    },
    
    PerformSmartDropListByLettersRequest: function(text, divId, objectType, poolType)
    {        
        if (smartDropManager.currentText == text)
        {
             text =text.replace(/&apos;/g, "'");

            var params = {
                            "letters": text,
                            "divId": divId,
                            "entityType": objectType,
                            "poolType": poolType
                        };
            
            smartDropManager.AbortAjax();
            //call a new request
            smartDropManager.currentAjaxRequest = 
                $j.ajax({
                    type: "GET",
                    url: "Services/SearchEngineService.asmx/GetSmartDropListByLetters",
                    data: params,
                    success: smartDropManager.GetSmartDropListByLetters_jQueryAjax_Complete
                });
        }
    },
       
    AbortAjax:function()
    {
       //kill the running request
        if (smartDropManager.currentAjaxRequest != null)
        {
            smartDropManager.currentAjaxRequest.abort();
        }
    },
       
    CheckDivDisplay: function(divId, objectType, poolType)
    {
        if (document.getElementById(divId).className == 'smartDrop_div_show')
        {
            // hide
            smartDropManager.HideDiv(divId);
        }
        else
        {
            // Hide any open drops
            smartDropManager.HideDrops();

            // Get list for requested drop
            smartDropManager.GetSmartDropListByLetters('', divId, objectType, poolType);
        }
    },

    GetSmartDropListByLetters_jQueryAjax_Complete: function(args,status)
    {
        var result = $j(args);
        var targetDivName =result.find("Target").text();
        var resultHtml =result.find("Result").text();
        
        smartDropManager.OpenSmartDropList(targetDivName,resultHtml);
        
    },
    
//    GetSmartDropListByLetters_Complete: function(args)
//    {
//        if (args != null)
//        {
//            smartDropManager.OpenSmartDropList(args.Target,args.Result);
//        }
//    },
    
    OpenSmartDropList: function(listDivName, html)
    {
        var target = document.getElementById(listDivName);
        
        if (html != '')
        {
            smartDropManager.ShowDiv(target);
            target.innerHTML = html;
        }
        else
        {
            smartDropManager.HideDiv(listDivName);
        }
    },

    // Sets an ID according to selected text, or deletes text if no ID found
    // This method occurs onBlur from a smartDrop's input field, if the smartDrop is flagged as "SelectionRequired"
    // (because a valid item must be selected)
    SetSelectionId: function(txtId, divId, objectType, poolType)
    {
        //alert('SetSelectionId called');
        var text = document.getElementById(txtId).value;

        if (text == '')
        {
            //document.getElementById(smartDropManager.dropsArray[divId].valueId).value = 0;
            smartDropManager.SetSmartDropValue(divId, 0);

            smartDropManager.isWorking = false;
            return;
        }

        SearchEngineService.GetSmartDropIdByLetters
        (
            text,
            divId,
            objectType,
            poolType,
            smartDropManager.SetSelectionId_Complete
	    );
    },

    SetSelectionId_Complete: function(args)
    {
        if (args.Result != null)
            smartDropManager.SetSmartDropSelectionNoHide(args.Result.Value, args.Result.Key, args.Target, false);
        else
            smartDropManager.SetSmartDropSelectionNoHide('', 0, args.Target, false);

        smartDropManager.isWorking = false;
    },

    // Check if user clicked outside of a smartDrop.  If so, hide all smartDrops.
    CheckExternalClick: function(event)
    {
        var target = $j(event.target);
        var parents = target.parents(".smartDropTable");

        if (target.parents(".smartDropTable").length == 0)
            smartDropManager.HideDrops();
    },

    ClearAllDrops: function()
    {
        for (var id in this.dropsArray)
        {
            smartDropManager.ClearSelection(id);
        }

        smartDropManager.isWorking = false;
    },

    // Clear a smartDrop's selection (id and text)
    ClearSelection: function(divId)
    {
        document.getElementById(smartDropManager.dropsArray[divId].txtId).value = '';
        smartDropManager.SetSmartDropValue(divId, 0);
    },

    ValidateBeforeSubmit: function(id)
    {
        if (smartDropManager.isWorking)
        {
            //alert('calling wait for submit');
            window.setTimeout("smartDropManager.WaitForSubmit('" + id + "')", 50);
            return false;
        }
        else
        {
            return true;
        }
    },

    WaitForSubmit: function(id)
    {
        //alert('wait for submit called.  smartDropManager.isWorking=' + smartDropManager.isWorking);

        if (smartDropManager.isWorking)
        {
            window.setTimeout("smartDropManager.WaitForSubmit('" + id + "')", 50);
        }
        else
        {
            var sender = document.getElementById(id);

            if (sender.click) // imageButton or IE
                sender.click();
            else // linkButton and not IE
            {
                var func = sender.href;

                if (func.indexOf('javascript:') == 0)
                    func = func.substring(11);

                eval(func);
            }
        }
    },

    //-------------------------------------------------------------------------------------------------
    //  IE div overlap fix
    //-------------------------------------------------------------------------------------------------   

    IsIE: function()
    {
        if (!browserDetect.initialized)
            browserDetect.init();

        return (browserDetect.browser == 'Explorer' && browserDetect.version < 7);
    },

    RemoveMask: function(divId)
    {
        if (smartDropManager.masks[divId] != null)
        {
            var mask = smartDropManager.masks[divId];
            document.body.removeChild(mask);
            smartDropManager.masks[divId] = null;
        }
    },

    SetMask: function(divId)
    {
        if (smartDropManager.masks[divId] == null)
        {
            var div = document.getElementById(divId);
            //Increase default zIndex of div by 1, so that DIV appears before IFrame
            div.style.zIndex = div.style.zIndex + 1;

            var iFrame = document.createElement('IFRAME');
            iFrame.setAttribute('src', '');

            //Match IFrame position with div's
            iFrame.style.position = 'absolute';
            iFrame.style.left = div.offsetLeft + 'px';
            iFrame.style.top = div.offsetTop + 'px';
            iFrame.style.width = div.offsetWidth + 'px';
            iFrame.style.height = div.offsetHeight + 'px';

            document.body.appendChild(iFrame);

            // Save iFrame object, so it can be removed when div is hidden 
            smartDropManager.masks[div.id] = iFrame;
        }
    },

    //-------------------------------------------------------------------------------------------------
    //  Simple Drop functionality
    //-------------------------------------------------------------------------------------------------   
    //law clauses drop functionality
    GetLawClausesList: function(lawId, divId)
    {
        window.setTimeout("smartDropManager.PerformGetLawClausesListRequest('"+lawId+"', '"+divId+"')",INTER_KEY_INTERVAL) ;
    },
    
    PerformGetLawClausesListRequest: function(lawId, divId)
    {        
           var params = {
                            "lawId": lawId,
                            "divId": divId
                        };
            
            smartDropManager.AbortAjax();
            //call a new request
            smartDropManager.currentAjaxRequest = 
                $j.ajax({
                    type: "GET",
                    url: "Services/SearchEngineService.asmx/GetSmartDropLawClauses",
                    data: params,
                    success: smartDropManager.GetSmartDropListByLetters_jQueryAjax_Complete
                });
    },
    
    //folder smart drop functionality
    GetFoldersList: function(text, divId)
    {
        text = text.replace(/'/g, "&apos;");
        smartDropManager.currentText = text;
        window.setTimeout("smartDropManager.PerformGetFoldersListRequest('"+text+"', '"+divId+"')",INTER_KEY_INTERVAL) ;
    },
    
    PerformGetFoldersListRequest: function(text, divId)
    {        
        if (smartDropManager.currentText == text)
        { 
             var params = {
                            "divId": divId
                        };
            
            smartDropManager.AbortAjax();
            //call a new request
            smartDropManager.currentAjaxRequest = 
                $j.ajax({
                    type: "GET",
                    url: "Services/SearchEngineService.asmx/GetSmartDropFoldersList",
                    data: params,
                    success: smartDropManager.GetSmartDropListByLetters_jQueryAjax_Complete
                });
        }
    }
};

// Add event to close divs on external click or on focus in another input
$j(document).ready(function()
{
    $j(document.body).mousedown(smartDropManager.CheckExternalClick);
    $j(':input').focus(function() { smartDropManager.HideDrops(); });
});


