﻿/*
 *  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();
        }
    }
}


var animationOut = null;         //Instantiate
var animationIn = null;         //Instantiate

function fadeOut(param) {
    if (animationOut == null) {
        animationOut = new $AA.FadeAnimation();
        animationIn = new $AA.FadeAnimation();

        var obj = $get('scrollbar_container');                            //This is a shortcut for document.getElementById. It will return the javascript element. This is the element that you want to fade.
        
        animationOut.set_target(obj);                       //An animation has to have a target to act upon.
        animationOut.set_effect($AA.FadeEffect.FadeOut);    //This determines whether a fade out or fade in is going to be executed.
        animationOut.set_duration(0.5);                          //How long the animation will last.
        animationOut.set_fps(25);                              //How many frames per second the animation should execute.

        //See notes on the fadeOut function.
        var obj = $get('scrollbar_container');

        animationIn.set_target(obj);
        animationIn.set_effect($AA.FadeEffect.FadeIn);
        animationIn.set_duration(0.5);
        animationIn.set_fps(25);
    }        
    
    animationOut.stop();
    animationIn.stop();

    animationOut.remove_ended(moveLeft);
    animationOut.remove_ended(moveRight);

    if (param == 'left') {
        animationOut.add_ended(moveLeft);
    }
    else {
        animationOut.add_ended(moveRight);
    }
    animationOut.play();                                   //Once everything is setup, it can be executed.
}

function fadeIn() {
    //var animation = new $AA.InterpolatedAnimation(obj, 2, 25, "scrollLeft");
    animationIn.play();
}

function show(a) {
    var link = $get("ctl00_ContentPlaceHolder1_imgbig");
    var bigimage = link.childNodes[0];
    var imageinfo = $get("imageinfo");

    link.href = a.href;
    a = a.childNodes[0];

    bigimage.src = a.src;
    bigimage.alt = a.alt;
    imageinfo.innerHTML = $get("desc_" + a.alt).innerHTML;
}

var scrollID = null;

////////////////////////////////////////////////////////////////////////////////
function scroll() {

    var test = $get('scrollbar_container');

    if (test != null) {
        $addHandler($get('ctl00_ContentPlaceHolder1_lvImages_scroll_left'), 'click', scrollLeft);


        $addHandler($get('ctl00_ContentPlaceHolder1_lvImages_scroll_right'), 'click', scrollRight);
    }

}

function scrollLeft() {
    fadeOut('left');
}

function scrollRight() {
    fadeOut('right');
}

function moveLeft() {
    animationOut.remove_ended(moveLeft);
    
    //clearInterval(scrollID);
    var scrollElementID = 'scrollbar_container';

    var scrollElement = $get(scrollElementID);
    var n = scrollElement.scrollLeft;

    var newPosition = n - 398;
    if (newPosition < 0) newPosition = scrollElement.scrollWidth;

    scrollElement.scrollLeft = newPosition;
    fadeIn();
    //scrollID = setInterval("NiceScroll('" + scrollElementID + "', '" + newPosition + "', 'left')", 10);
}

function moveRight() {
    animationOut.remove_ended(moveLeft);
    
    //clearInterval(scrollID);
    var scrollElementID = 'scrollbar_container';

    var scrollElement = $get(scrollElementID);

    var n = scrollElement.scrollLeft;

    var newPosition = n + 398;
    if (newPosition > scrollElement.scrollWidth) newPosition = 0;

    scrollElement.scrollLeft = newPosition;
    fadeIn();
    //scrollID = setInterval("NiceScroll('" + scrollElementID + "', '" + newPosition + "', 'right')", 10);
}


function NiceScroll(containerID, finishPoint, side) {
    var scrollElement = $get(containerID);

    var newPosition = 0;

    var moveOffset = 398;

    if (side == 'right') {
        newPosition = scrollElement.scrollLeft + moveOffset;
        if (newPosition > finishPoint) newPosition = finishPoint;
    }
    else {
        newPosition = scrollElement.scrollLeft - moveOffset;
        if (newPosition <= 0) newPosition = scrollElement.scrollWidth;
    }

    scrollElement.scrollLeft = newPosition;

    if (newPosition == finishPoint) {
        clearInterval(scrollID);
    }
}

/*                         Fin Scroll Images                               */


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*@cc_on@*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        init(); // call the onload handler
    }
};
/*@end@*/

if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            clearInterval(_timer);
            init(); // call the onload handler
        }
    }, 10);
}

window.onload = init;


function init() {
    // quit if this function has already been called
    if (arguments.callee.done) return;

    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;

    // do stuff
    scroll();

    shortcutListener.init();
};


/*
	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);            
    }
}

var lastpostbackelement;

function beginRequest(sender, args)
{
    if (args != null) {
        if (args._postBackElement != null) {
            lastpostbackelement = args._postBackElement;

            args._postBackElement.disabled = true;
        }
    }

}
function pageLoadingHandler(sender, args) 
{

}

function endRequest(sender, args) 
{
    if (args != null) {

        if (args._postBackElement != null) {
            args._postBackElement.disabled = false;
        }
        else {
            if (lastpostbackelement != null) {
                lastpostbackelement.disabled = false;
                lastpostbackelement = null;
            }
        }
    }    
}          

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;
}