﻿function cancelBubbling(e) {
    if (e) {
        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            e.cancelBubble = true;
            e.returnValue = false;
        }
    }

    return false;
}

function sleep(milliseconds) {
    var start = new Date().getTime();
    
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

String.prototype.isDigit = function() {
    return ((this >= '0') && (this <= '9'));
};

String.prototype.isLetter = function() {
    return Boolean(!this.match(/[^A-Za-z]/));
};

function getUTCFromLocale(dateLocale) {
    var localTime = dateLocale.getTime();
    var localOffset = dateLocale.getTimezoneOffset() * 60000;
    var utc = localTime + localOffset;
    return new Date(utc);
};

Number.prototype.round = function(decimalDigitsCount) {
    var multiplyFactor = 1;

    if (arguments.length > 0) {
        for (var i = 1; i <= decimalDigitsCount; i++) {
            multiplyFactor *= 10;
        }
    }

    return (Math.round(this * multiplyFactor) / multiplyFactor);
};

Number.prototype.isInteger = function() {
    return !(this % 1);
}

/* Start of ASP.NET Built-in validation refactoring */

if (typeof RequiredFieldValidatorEvaluateIsValid == 'function') {
    __oldRequiredFieldValidatorEvaluateIsValid = RequiredFieldValidatorEvaluateIsValid;
    RequiredFieldValidatorEvaluateIsValid = __newRequiredFieldValidatorEvaluateIsValid;
}

if (typeof CustomValidatorEvaluateIsValid == 'function') {
    __oldCustomValidatorEvaluateIsValid = CustomValidatorEvaluateIsValid;
    CustomValidatorEvaluateIsValid = __newCustomValidatorEvaluateIsValid;
}

if (typeof RegularExpressionValidatorEvaluateIsValid == 'function') {
    __oldRegularExpressionValidatorEvaluateIsValid = RegularExpressionValidatorEvaluateIsValid;
    RegularExpressionValidatorEvaluateIsValid = __newRegularExpressionValidatorEvaluateIsValid;
}

if (typeof CompareValidatorEvaluateIsValid == 'function') {
    __oldCompareValidatorEvaluateIsValid = CompareValidatorEvaluateIsValid;
    CompareValidatorEvaluateIsValid = __newCompareValidatorEvaluateIsValid;
}

function __newRequiredFieldValidatorEvaluateIsValid(val) {
    var isValid = __oldRequiredFieldValidatorEvaluateIsValid(val);
    setInputFieldCssClass(val.controltovalidate, isValid);
    return isValid;
}

function __newRegularExpressionValidatorEvaluateIsValid(val) {
    var isValid = __oldRegularExpressionValidatorEvaluateIsValid(val);
    setInputFieldCssClass(val.controltovalidate, isValid);
    return isValid;
}

function __newCompareValidatorEvaluateIsValid(val) {
    var isValid = __oldCompareValidatorEvaluateIsValid(val);
    setInputFieldCssClass(val.controltovalidate, isValid);
    return isValid;
}

function __newCustomValidatorEvaluateIsValid(val) {
    var isValid = __oldCustomValidatorEvaluateIsValid(val);
    setInputFieldCssClass(val.controltovalidate, isValid);
    return isValid;
}

function setInputFieldCssClass(controlToValidateID, isValid) {
    var controlToValidate = $get(controlToValidateID);

    if (controlToValidate &&
        (typeof _errorCssClassName != 'undefined')) {
        if (!isValid) {
            if (!Sys.UI.DomElement.containsCssClass(controlToValidate, _errorCssClassName)) {
                Sys.UI.DomElement.addCssClass(controlToValidate, _errorCssClassName);
            }
        }
        else {
            if (Sys.UI.DomElement.containsCssClass(controlToValidate, _errorCssClassName)) {
                Sys.UI.DomElement.removeCssClass(controlToValidate, _errorCssClassName);
            }
        }
    }
}

if (typeof ValidatorUpdateDisplay == 'function') {
    __oldValidatorUpdateDisplay = ValidatorUpdateDisplay;
    ValidatorUpdateDisplay = __newValidatorUpdateDisplay;
}

function __newValidatorUpdateDisplay(val) {
    __oldValidatorUpdateDisplay(val);
    val.style.display = val.isvalid ? 'none' : 'inline';
}

/* End of ASP.NET Built-in validation refactoring */

/* Browser Helpers */
function isIE7() {
    return (Sys.Browser.name == 'Microsoft Internet Explorer') && (Sys.Browser.version < 8) ? true : false;
}

/* HACK */
function ___doPostBack(eventTarget, eventArgument) {
    if (theForm) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
}
/* End Browser Helpers */

/* Html encoding */
function htmlEncode(source, display, tabs) {
    function special(source) {
        var result = '';
        
        for (var i = 0; i < source.length; i++) {
            var c = source.charAt(i);
            
            if (c < ' ' || c > '~') {
                c = '&#' + c.charCodeAt() + ';';
            }
            
            result += c;
        }
        
        return result;
    }

    function format(source) {
        tabs = (tabs >= 0) ? Math.floor(tabs) : 4;
        var lines = source.split(/\r\n|\r|\n/);

        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            var newLine = '';

            for (var p = 0; p < line.length; p++) {
                var c = line.charAt(p);
                
                if (c === '\t') {
                    var spaces = tabs - (newLine.length % tabs);
                    
                    for (var s = 0; s < spaces; s++) {
                        newLine += ' ';
                    }
                }
                else {
                    newLine += c;
                }
            }

            newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');
            lines[i] = newLine;
        }

        var result = lines.join('<br />');
        result = result.replace(/  /g, ' &nbsp;');

        return result;
    }

    var result = source;
    result = result.replace(/\&/g, '&amp;');
    result = result.replace(/\</g, '&lt;');
    result = result.replace(/\>/g, '&gt;');

    if (display) {
        result = format(result);
    }
    else {
        result = result.replace(new RegExp('"', 'g'), '&quot;');
    }

    result = special(result);
    return result;
}
/* End Html encoding */

/* Url encoding */
function urlEncode (source) {
    source = escape(source);
    return source.replace(/[*+\/@]|%20/g,
                          function (s) {
                                switch (s) {
                                    case "*":
                                        s = "%2A";
                                        break;
                                    case "+":
                                        s = "%2B";
                                        break;
                                    case "/":
                                        s = "%2F";
                                        break;
                                    case "@":
                                        s = "%40";
                                        break;
                                    case "%20":
                                        s = "+";
                                        break;
                                }
                                
                                return s;
                        });
}
/* End Url encoding */

if (typeof (Sys) != 'undefined') {
    Sys.UI.DomElement.removeAllChildren = function(parentElement) {
        if (!parentElement) {
            return;
        }

        while (parentElement.hasChildNodes()) {
            parentElement.removeChild(parentElement.firstChild);
        }
    }
}

/* Pages API*/

/// <summary>
/// Mostra o nasconde un elemento e sostituisce l'immagine dell'elemento
/// che ha generato l'evento.
/// </summary>
/// <param name="sender">
/// L'elemento che ha generato l'evento.
/// </param>
/// <param name="elementID">
/// L'elemento da mostrare/nascondere.
/// </param>
/// <param name="imgExpand">
/// Opzionale. Specifica l'url dell'immagine relativa all'espansione.
/// </param>
/// <param name="imgCollapse">
/// Opzionale. Specifica l'url dell'immagine relativa alla compressione.
/// </param>
/// <example>
/// <img onclick="howHide(this, 'divLanguages');" alt="" />
/// <div id="divLanguages">
///     Italiano<br />
///     Inglese
/// </div>
/// <img onclick="howHide(this, 'divContent', '/Images/expand.png', '/Images/collapse.png');" alt="" />
/// <div id="divContent">
///     Con content to hide/show.
/// </div>
/// </example>
/// <remarks>
/// Se si utilizza l'attributo "onclick", si passa come
/// primo parametro, la parola chiave "this".
/// </remarks>

var _showHideLocked = false;

function showHide(sender, elementID, imgExpand, imgCollapse) {
    if (!_showHideLocked) {
        var elj = $('#' + elementID);
        var el = $get(elementID);
        var isDown = (el.style.display == 'none') ? false : true;
        var img1 = (arguments.length >= 3) ? imgExpand : '/App_Themes/Default/images/Icons/plus.png';
        var img2 = (arguments.length >= 4) ? imgCollapse : '/App_Themes/Default/images/Icons/minus.png';




        //var el = $get(elementID);
        //var elj = $('#' + elementID);
        var img = (sender.nodeName == 'IMG') ? sender : sender.getElementsByTagName('img')[0];

        if (img) {
            if (Sys.Browser.name == 'Microsoft Internet Explorer') {
                //img.src = (el.style.display == 'none') ? img1 : img2;
                img.src = isDown ? img1 : img2;
            }
            else {
                //img.setAttribute('src', (el.style.display == 'none') ? img1 : img2);
                img.setAttribute('src', isDown ? img1 : img2);
            }
        }
        
        if (el && elj) {
            _showHideLocked = true;
            elj.slideToggle('fast', function() {
                _showHideLocked = false;
            });

            //el.style.display = (el.style.display == 'none') ? '' : 'none';
        }
    }
}


/// <summary>
/// Apre una modal popup.
/// </summary>
/// <param name="dialogID">
/// L'id dell'elemento che rappresenta la modal popup.
/// </param>
function openDialog(dialogID, e) {
    if (e && (typeof(e.preventDefault) == 'function')) {
        e.preventDefault();
    }
    
    var d = $get(dialogID);

    if (d) {
        $('#' + d.id).modal({ onOpen: function(dialog) {
            dialog.overlay.fadeIn('slow', function() {
                dialog.data.hide();
                dialog.container.fadeIn('slow', function() {
                    dialog.data.slideDown('slow');
                });
            });
        }
        });
    }
}

/// <summary>
/// Esegue il fade di un elemento.
/// </summary>
/// <param name="testDiv">
/// L'elemento sul quale applicare il fading.
/// </param>
//<a
//    onmouseout="$('#testDiv').fadeOut('slow');"
//    onmouseover="$('#testDiv').fadeIn('slow');">
//    OVERTHIS</a>
//<div
//    id="testDiv"
//    style="display : none; background-color : Red; width : 200px; height : 100px;">
//    Hello world!
//</div>
function fadeElement(elementID, fadeType) {
    var el = $get(elementID);
    
    if (el) {
        if (!el.locked) {
            el.locked = true;
            
            if (fadeType == 'out') {
                $('#' + el.id).fadeOut('slow', function() { el.locked = false; });
            }
            else {
                $('#' + el.id).fadeIn('slow', function() {
                    el.locked = false;
                    
                    if (el.queue) {
                        el.queue = false;
                        el.locked = true;
                        $('#' + el.id).fadeOut('slow', function() { el.locked = false; });
                    }
                });
            }
        }
        else {
            el.queue = true;
        }
    }
}

/* End of Pages API*/
