﻿/*
*  Acunote Shortcuts.
*  Javascript keyboard shortcuts mini-framework.
*
*  Copyright (c) 2007-2008 Pluron, Inc.
*
*  Permission is hereby granted, free of charge, to any person obtaining
*  a copy of this software and associated documentation files (the
*  "Software"), to deal in the Software without restriction, including
*  without limitation the rights to use, copy, modify, merge, publish,
*  distribute, sublicense, and/or sell copies of the Software, and to
*  permit persons to whom the Software is furnished to do so, subject to
*  the following conditions:
*
*  The above copyright notice and this permission notice shall be
*  included in all copies or substantial portions of the Software.
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
*  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
*  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
*  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
*  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

var shortcutListener = {

    listen: true,

    shortcut: null,
    combination: '',
    lastKeypress: 0,
    clearTimeout: 2000,

    // Keys we don't listen 
    keys: {
        KEY_BACKSPACE: 8,
        KEY_TAB: 9,
        KEY_ENTER: 13,
        KEY_SHIFT: 16,
        KEY_CTRL: 17,
        KEY_ALT: 18,
        KEY_SPACE: 32,
        KEY_LEFT: 37,
        KEY_UP: 38,
        KEY_RIGHT: 39,
        KEY_DOWN: 40,
        KEY_DELETE: 46,
        KEY_HOME: 36,
        KEY_END: 35,
        KEY_PAGEUP: 33,
        KEY_PAGEDOWN: 34
    },

    init: function() {
        if (!window.SHORTCUTS) return false;
        this.createStatusArea();
        this.setObserver();
    },

    isInputTarget: function(e) {
        var target = e.target || e.srcElement;
        if (target && target.nodeName) {
            var targetNodeName = target.nodeName.toLowerCase();
            if (targetNodeName == "textarea" || targetNodeName == "select" ||
                (targetNodeName == "input" && target.type &&
                    (target.type.toLowerCase() == "text" ||
                         target.type.toLowerCase() == "password"))
                             ) {
                return true;
            }
        }
        return false;
    },

    stopEvent: function(event) {
        if (event.preventDefault) {
            event.preventDefault();
            event.stopPropagation();
        } else {
            event.returnValue = false;
            event.cancelBubble = true;
        }
    },


    // shortcut notification/status area
    createStatusArea: function() {
        var area = document.createElement('div');
        area.setAttribute('id', 'shortcut_status');
        area.style.display = 'none';
        document.body.appendChild(area);
    },

    showStatus: function() {
        document.getElementById('shortcut_status').style.display = '';
    },

    hideStatus: function() {
        document.getElementById('shortcut_status').style.display = 'none';
    },

    showCombination: function() {
        var bar = document.getElementById('shortcut_status');
        bar.innerHTML = this.combination;
        this.showStatus();
    },

    // This method creates event observer for the whole document
    // This is the common way of setting event observer that works 
    // in all modern brwosers with "keypress" fix for
    // Konqueror/Safari/KHTML borrowed from Prototype.js
    setObserver: function() {
        var name = 'keypress';
        if (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || document.detachEvent) {
            name = 'keydown';
        }
        if (document.addEventListener) {
            document.addEventListener(name, function(e) { shortcutListener.keyCollector(e) }, false);
        } else if (document.attachEvent) {
            document.attachEvent('on' + name, function(e) { shortcutListener.keyCollector(e) });
        }
    },

    // Key press collector. Collects all keypresses into combination 
    // and checks it we have action for it
    keyCollector: function(e) {
        // do not listen if no shortcuts defined
        if (!window.SHORTCUTS) return false;
        // do not listen if listener was explicitly turned off
        if (!shortcutListener.listen) return false;
        // leave modifiers for browser
        if (e.altKey || e.ctrlKey || e.metaKey) return false;
        var keyCode = e.keyCode;
        // do not listen for Ctrl, Alt, Tab, Space, Esc and others
        for (var key in this.keys) {
            if (e.keyCode == this.keys[key]) return false;
        }
        // do not listen for functional keys
        if (navigator.userAgent.match(/Gecko/)) {
            if (e.keyCode >= 112 && e.keyCode <= 123) return false;
        }

        var code = e.which ? e.which : e.keyCode

        // do not listen in input/select/textarea fields
        if (this.isInputTarget(e)) return false;

        //Process Custom keys first as code
        if (shortcutListener.processCustom(code)) {
            shortcutListener.stopEvent(e);
            return false;
        }

        // get letter pressed for different browsers
        var letter = String.fromCharCode(code).toLowerCase();
        if (e.shiftKey) letter = letter.toUpperCase();
        if (shortcutListener.process(letter)) shortcutListener.stopEvent(e);
    },

    // process custom keys
    processCustom: function(code) {
        if (!window.SHORTCUTS) return false;
        if (!shortcutListener.listen) return false;

        // filter codes to listen        
        if (code == 27) {
            // start from the begining
            shortcutListener.shortcut = SHORTCUTS;
            // if unknown letter then say goodbye
            if (!shortcutListener.shortcut[code]) return false
            if (typeof (shortcutListener.shortcut[code]) == "function") {
                shortcutListener.shortcut[code]();
                shortcutListener.clearCombination();

                return true;
            }
        }

        return false;
    },

    // process keys
    process: function(letter) {
        if (!window.SHORTCUTS) return false;
        if (!shortcutListener.listen) return false;
        // if no combination then start from the begining
        if (!shortcutListener.shortcut) { shortcutListener.shortcut = SHORTCUTS; }
        // if unknown letter then say goodbye
        if (!shortcutListener.shortcut[letter]) return false
        if (typeof (shortcutListener.shortcut[letter]) == "function") {
            shortcutListener.shortcut[letter]();
            shortcutListener.clearCombination();
        } else {
            shortcutListener.shortcut = shortcutListener.shortcut[letter];
            // append combination
            shortcutListener.combination = shortcutListener.combination + letter;
            if (shortcutListener.combination.length > 0) {
                shortcutListener.showCombination();
                // save last keypress timestamp (for autoclear)
                var d = new Date;
                shortcutListener.lastKeypress = d.getTime();
                // autoclear combination in 2 seconds
                setTimeout("shortcutListener.clearCombinationOnTimeout()", shortcutListener.clearTimeout);
            };
        }
        return true;
    },

    // clear combination
    clearCombination: function() {
        shortcutListener.shortcut = null;
        shortcutListener.combination = '';
        this.hideStatus();
    },

    clearCombinationOnTimeout: function() {
        var d = new Date;
        // check if last keypress was earlier than (now - clearTimeout)
        // 100ms here is used just to be sure that this will work in superfast browsers :)
        if ((d.getTime() - shortcutListener.lastKeypress) >= (shortcutListener.clearTimeout - 100)) {
            shortcutListener.clearCombination();
        }
    }
}


function FillMenu()
{
    DetailsMenu.fillMenu(FillMenuHandler);       
}

function FillMenuHandler(result)
{
    $get('adminDetailMenu').innerHTML = result;
    
    FillSubMenu();
}

function FillSubMenu()
{
    var value = GetMenuValue();
    
    DetailsMenu.fillSubMenu(value, FillSubMenuHandler);
}

function FillSubMenuHandler(result)
{
    $get('adminDetailSubMenu').innerHTML = result;
}

function AddMenu()
{
    var id = $get('txtMenuID').value;
    var order = $get('txtMenuOrder').value;

    DetailsMenu.addMenu(id, order, FillMenuHandler);       
}

function AddSubMenu()
{
    var MenuUID = GetMenuValue();

    if( MenuUID == null )
    {
        alert('Select Menu!');
        return;
    }
    
    var submenuid = $get('txtSubMenuID').value;
    var submenuorder = $get('txtSubMenuOrder').value;

    DetailsMenu.addSubMenu(MenuUID, submenuid, submenuorder, FillSubMenuHandler);       
}

function RemoveMenu()
{
    DetailsMenu.removeMenu(GetMenuValue(), FillMenuHandler);
}

function RemoveSubMenu()
{
    DetailsMenu.removeSubMenu(GetSubMenuValue(), FillSubMenuHandler);
}

function GetMenuValue()
{
    var menu = $get('ctl00_ContentPlaceHolder1_lbMenu');
    
    if( menu.selectedIndex != -1 )
    {
        return menu.options[menu.selectedIndex].value;
    }
    
    return null;
}

function GetSubMenuValue()
{
    var menu = $get('ctl00_ContentPlaceHolder1_lbSubMenu');
    
    if( menu.selectedIndex != -1 )
    {
        return menu.options[menu.selectedIndex].value;
    }
    
    return null;
}

/*
	parseUri 1.2.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function pageLoad(sender, args){  
    if(!args.get_isPartialLoad()){  
        //  register for our events
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);    
        
        if( location.hash != null && location.hash != '' )
        {
            var new_pos = document.location.hash.substr(1,document.location.hash.length);            
            
            ShowDetail(new_pos);
            
            SetAccordionPosition();
        }
    }
}

function beginRequest(sender, args)
{

}

function pageLoadingHandler(sender, args) 
{

}

function endRequest(sender, args) 
{

}          

var SHORTCUTS = 
{
    'h': function() { ShowHideAdminLogin(); },
    27 : function() { HideAdminLogin(); }
}


function ShowHideAdminLogin()
{
    var adminlogin = $get('ctl00_adminlogin1_adminlogin');
    
    if( adminlogin != null )
    {
        if( adminlogin.style.display == '' )
        {   
            HideAdminLogin();
        }
        else
        {
            ShowAdminLogin();
        }
    }
}

function ShowAdminLogin()
{
    var adminlogin = $get('ctl00_adminlogin1_adminlogin');

    if( adminlogin != null )
    {
        adminlogin.style.display = '';
        
        var username = $get('ctl00_adminlogin1_LoginView1_txtUsername');
        
        if( username != null )
        {
            username.focus();
        }
    }
}

function HideAdminLogin()
{
    var adminlogin = $get('ctl00_adminlogin1_adminlogin');
    
    if( adminlogin != null )
    {
        adminlogin.style.display = 'none';
    }
}

var details_current = '0-clients-definition';

function ShowDetail(option)
{
    var optionObj = $get(option);    
    var current_option = $get(details_current);
    
    if( optionObj != null && current_option != null )
    {        
        Sys.UI.DomElement.addCssClass(current_option, 'hide');
        Sys.UI.DomElement.removeCssClass(optionObj, 'hide');
        
        details_current = option;
    }    
}

function GoToDeatil(option)
{
    window.location = 'details.aspx#' + option;
    
    ShowDetail(option);
}

function SetAccordionPosition()
{
    var accordion = $get('ctl00_ContentPlaceHolder1_Accordion1').AccordionBehavior;
 
    var saveDuration = accordion.get_TransitionDuration();
    
    accordion.set_TransitionDuration(1);
           
    accordion.set_SelectedIndex(details_current.charAt(0));
    
    accordion.set_TransitionDuration(saveDuration);
}

function ChangeLanguage( NewLanguage )
{
    var location = String(window.location);
    
    location = location.replace('/en/', '/' + NewLanguage + '/');    
    location = location.replace('/es/', '/' + NewLanguage + '/');
    location = location.replace('/sr/', '/' + NewLanguage + '/');
    
    window.location = location;

//    var items = parseUri(location);
////    
//    var directory = items.directory.split('/');
//    
////    location = location.replace('/en/', '/' + NewLanguage + '/');    
////    location = location.replace('/es/', '/' + NewLanguage + '/');
////    location = location.replace('/sr/', '/' + NewLanguage + '/');
//    
//    directory[1] = ''
////    
////    alert(items.directory);
}

function showLanguages() {
    document.getElementById("pnlLanguage").className = "divLanguageFalse";
    document.getElementById("pnlThreeLanguages").className = "divThreeLanguagesTrue";
}