﻿//-------------------------------------------------------------------------------------------------
//  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>',
    
    methods: [],
    defaultContainerId: '',
    intervals: [],

    // Initialize a defaultContainerId for the progress image
    Init: function(defaultContainerId)
    {
        this.defaultContainerId = defaultContainerId;
    },
    
    ShowProgress: function(method, containerId, wrapperStyle)
    {
        if(containerId == undefined && ajaxHelper.defaultContainerId == '')
            return; // no container found: return
            
        // Get container
        container = document.getElementById(containerId != undefined ? containerId : ajaxHelper.defaultContainerId);
        
        // Get progressImage div style
        wrapperStyle = wrapperStyle !== undefined ? wrapperStyle : ajaxHelper.wrapperStyle;
        
        // Save container in array
        this.methods[method] = container;
        
        if (container != null)
            container.innerHTML = this.progressImage.replace('{0}', wrapperStyle);
    },
    
    HideProgress: function(method, content)
    {
        this.methods[method].innerHTML = content;
    },
    
    ShowError: function(args)
    {
        alert("ארעה תקלה במהלך הפעולה האחרונה, אנא נסה שנית!");
        //alert("ארעה תקלה במהלך הפעולה האחרונה.  השגיעה: " + args);
    },
    
    // Begin polling for a result.
    // param "pollMethod": the delegated method (as a string) 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 (as a string) 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)
    }
}


//-------------------------------------------------------------------------------------------------
//  Common 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];
    }
}

function FailedCallback(error, userContext, methodName)
{
    try{ajaxHelper.HideProgress(methodName, '');}
    catch(e){}
    ajaxHelper.ShowError(error);
    
    if(smartDropManager)
        if(smartDropManager.isWorking)
            smartDropManager.isWorking = false;
}

// Loops through form elements and executes "foreachFunc" on each element of type "type" containing "name" in its name
function ExecFuncOnElements(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]);
            }
        }
    }
}

function ToggleCheckboxes(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;
            }
        }
    }
}

function HideElement(id)
{
    document.getElementById(id).style.display = 'none';
}

function ShowElement(id)
{
    document.getElementById(id).style.display = '';
}

// Toggle an element's display
function ToggleElement(id)
{
    var elem = document.getElementById(id);
    elem.style.display = elem.style.display == 'none' ? '' : 'none';
    
    return elem.style.display;
}

// Checks if the array contains a member 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
function ArrayIndexOf(arr, o)
{
    for(var i in arr)
    {
        if(arr[i] == o)
            return i;
    }
    
    return -1;
}

// 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: '',
    
    divs: {
        beforeId: '',
        afterId: ''
    },
    
    panels: {
        login: {id: '', active: true},
        forgotPass: {id: '', active: false}
    },

    Init: function(popupId, nameLblId, beforeId, afterId, loginId, forgotPassId)
    {
        this.popupId = popupId;
        this.nameLblId = nameLblId;
        this.divs.beforeId = beforeId;
        this.divs.afterId = afterId;
        this.panels.login.id = loginId;
        this.panels.forgotPass.id = forgotPassId;
    }, 
    
    // Hide login popup
    HidePopup: function()
    {
	    $find(loginManager.popupId).hide();
    },
    
    // Show login popup
    ShowPopup: function()
    {
	    $find(loginManager.popupId).show();
	    document.getElementById('loginTxt').focus();
    },
    
    // Switch between login div and forgotPass div
    SwitchPanels: function()
    {
        loginManager.panels.login.active = !loginManager.panels.login.active;
        loginManager.panels.forgotPass.active = !loginManager.panels.forgotPass.active;
        
        ToggleElement(loginManager.panels.login.id);
        ToggleElement(loginManager.panels.forgotPass.id);
    },
    
    // Show forgot password success message
    ShowForgotPassResult: function()
    {
        // Set label
        document.getElementById('emailLbl').innerHTML = document.getElementById("txtEmail").value;
    
        HideElement('forgotPassDiv');
        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
            loginManager.SwitchPanels();
    },
    
    // Display a message in the status label
    ShowStatusMessage: function(message)
    {
        document.getElementById('statusLbl').innerHTML = message;        
    }
}

function LoginUser()
{
    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('');
    
    SearchEngineService.LoginUser(username, password, doRememberPass, LoginUser_Complete);
}

function LoginUser_Complete(args)
{
    if(args.Result == true)
    {
        loginManager.HidePopup('popupId');
        HideElement(loginManager.divs.beforeId);
        ShowElement(loginManager.divs.afterId);
        document.getElementById(loginManager.nameLblId).innerHTML = args.Username;
        window.location.href = window.location.href;
    }
    else
    {
        // Show recieved message
        loginManager.ShowStatusMessage(args.Message);
    }    
}

function LogoutUser()
{
    SearchEngineService.LogoutUser(LogoutUser_Complete);
}

function LogoutUser_Complete(args)
{    
    if(args == true)
    {
        document.getElementById(loginManager.nameLblId).innerHTML = '';
        HideElement(loginManager.divs.afterId);
        ShowElement(loginManager.divs.beforeId);
        window.location.href = window.location.href;
    }
    else
    {
        // Show error
        ajaxHelper.ShowError(); 
    }   
}

function SendPasswordToClient()
{
    var email = document.getElementById("txtEmail").value;
    SearchEngineService.SendPasswordToClient(email, SendPasswordToClient_Complete);
}

function SendPasswordToClient_Complete(args)
{
    if(args.Result == true)
        loginManager.ShowForgotPassResult();
    else if(args.Result == false && args.Info == false)
        loginManager.ShowStatusMessage('כתובת דואר אלקטרונית לא נמצאה');
    else
        ajaxHelper.ShowError('!ארעה תקלה בעת שליחת המייל , אנא נסה שנית');
}


//-------------------------------------------------------------------------------------------------
//  Tabbing
//-------------------------------------------------------------------------------------------------

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: 'tabNarrow',
            firstActive: 'tabNarrowFirstActive',
            firstInactive: 'tabNarrowFirst'
        },
        wide:{
            active: 'tabWideActive',
            inactive: 'tabWide',
            firstActive: 'tabWideFirstActive',
            firstInactive: 'tabWideFirst'
        }
    }, 
    
    // 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
            }
        }
    }
}


//-------------------------------------------------------------------------------------------------
//  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"
		}
	]
};

function openDocumentWithAnchor(a , docId , artId)
{
    var i = "a";
	
    a.style.textDecoration="underline";
    a.href = "wfShowDocument.aspx?DocId="+docId+"&Ancr="+artId;
	a.target = "_blank";	                               
}

function JumpToAnchor(anchorName)
{
    var iFrame = document.getElementById('documentFrame');
    var regex = /^(.*?)(#.*)?$/;
    
    iFrame.src = iFrame.src.replace(regex, '$1#' + anchorName);
}