﻿//number picker JS
function attachNumberPicker(textboxID, plusImageID, minusImageID, initialValue, minValue, maxValue) {
    new NumberPicker(textboxID, plusImageID, minusImageID, initialValue, minValue, maxValue);
}

function NumberPicker(textboxID, plusImageID, minusImageID, initialValue, minValue, maxValue) {
    this.textBox = document.getElementById(textboxID);
    this.textBox.value = (initialValue) ? initialValue : '0';

    this.plusImage = document.getElementById(plusImageID);       
    this.minusImage = document.getElementById(minusImageID);    

    this.plusImage.style.position = 'relative'
    this.plusImage.style.left = '-16px';
    this.plusImage.style.top = '-6px';
    this.minusImage.style.position = 'relative'
    this.minusImage.style.left = '-31px';
    this.minusImage.style.top = '2px';
    
    this.minValue = minValue;
    this.maxValue = maxValue;

    this.mouseDown = false;

    addListener(this.textBox, 'keydown', ensureNumeric);
    addListener(this.plusImage, 'mousedown', this.plusDown.bind(this));
    addListener(this.minusImage, 'mousedown', this.minusDown.bind(this));
    addListener(this.plusImage, 'mouseup', this.stopLoops.bind(this));
    addListener(this.minusImage, 'mouseup', this.stopLoops.bind(this));
    addListener(this.plusImage, 'mouseout', this.endHoverAndLoops.bind(this));
    addListener(this.minusImage, 'mouseout', this.endHoverAndLoops.bind(this));
    addListener(this.plusImage, 'mouseover', this.startHover.bind(this));
    addListener(this.minusImage, 'mouseover', this.startHover.bind(this))    
}

NumberPicker.prototype.getCurrentValue = function() {
    var currentVal = parseInt(this.textBox.value);
    if (!isNaN(currentVal)) {
        return currentVal;
    }
    else {
        return 0;
    }
}

NumberPicker.prototype.setCurrentValue = function(newValue) {
    if (
    (!isNaN(newValue))
    &&
    (newValue >= this.minValue)
    &&
    (newValue <= this.maxValue)
    ) {
        this.textBox.value = newValue;
        return true;
    }
    else
    {
        return false;
    }
}

NumberPicker.prototype.startValueChange = function(increment) {
    this.mouseDown = true; //mouse is down!
    this.loopCounter = 0; //numer of iterations
    this.stepSize = (increment) ? 1 : -1; //set initial increment/decrement value
    
    this.loopValueChange();
}

NumberPicker.prototype.loopValueChange = function() {
    this.loopCounter++;

    if ((this.loopCounter % 100) == 0) {
        this.stepSize = this.stepSize * 2;
    }

    var val = this.getCurrentValue();
    if ((this.mouseDown) && (this.setCurrentValue(val + this.stepSize))) {
        window.setTimeout(this.loopValueChange.bind(this), 500 / (this.loopCounter / 2)); 
    }
}

NumberPicker.prototype.plusDown = function(e) {
    this.startValueChange(true);
}

NumberPicker.prototype.minusDown = function(e) {
    this.startValueChange(false);
}

NumberPicker.prototype.stopLoops = function(e) {
    this.mouseDown = false;
}

NumberPicker.prototype.endHoverAndLoops = function(e) {
    var sndr = getSender(e);
    sndr.src = sndr.getAttribute('defaultimage');

    this.stopLoops(e);
}

NumberPicker.prototype.startHover = function(e) {
    var sndr = getSender(e);
    sndr.src = sndr.getAttribute('hoverimage');
}

//various/helper functions..
function ensureNumeric(e) {
    var evn = (e) ? e : window.event;
    if (
        ((!evn.shiftKey) && (evn.keyCode >= 48) && (evn.keyCode <= 57)) ||
        ((!evn.shiftKey) && (evn.keyCode >= 96) && (evn.keyCode <= 105)) ||
        (evn.keyCode == 8) || (evn.keyCode == 9) || (evn.keyCode == 13) || (evn.keyCode == 37) || (evn.keyCode == 39) || (evn.keyCode == 46) || (evn.keyCode == 144)
    )
    { evn.returnValue = true; return true; }
    else { evn.returnValue = false; return false; }
}

function addListener(elm, evn, deleg) {
    if (window.attachEvent) {
        elm.attachEvent("on" + evn, deleg);
    }
    else {
        elm.addEventListener(evn, deleg, true);
    }
}

Function.prototype.bind = function(obj) { 
    var method = this, 
    temp = function() { 
    return method.apply(obj, arguments); 
    }; 

    return temp;
}

function getSender(e) {
    var evn = (e) ? e : window.event;
    var sndr = (evn.srcElement) ? evn.srcElement : evn.target;
    return sndr;
}

function checkUniqueValue(propertyName, keyValue, objectType, currentValue, baseUrl) {
    //prototype is used in backend :-(
    if (top.Ajax) {
        var url = baseUrl + 'Validation.ashx?validationtype=Unique&property=' + propertyName + '&key=' + keyValue + '&objecttype=' + objectType + '&value=' + currentValue;
        var response = new top.Ajax.Request(url, { method: 'get', asynchronous: false }).transport.responseText;
        return eval("(" + response + ")").IsValid;
    }
    else {
        return true;
    }
}

if (typeof (openFileDialog) != 'function') {

    function openFileDialog(moduleurl, idfield, displayfield) {
        var url = '';
        var height = 440;
        var width = 610;
        var vleft = (screen.availWidth / 2) - (width / 2);
        var vtop = (screen.availHeight / 2) - (height / 2);

        var idvalue = document.getElementById(idfield).value;
        var dispvalue = document.getElementById(displayfield).value;

        var url = moduleurl + "&idfield=" + idfield + "&displayfield=" + displayfield;

        var baseUrl = null;

        try {
            if (window.top && window.top.mm_baseUrl)
                baseUrl = window.top.mm_baseUrl;
            else if (window.opener && window.opener.top.mm_baseUrl)
                baseUrl = window.opener.top.mm_baseUrl;
            else if (window.opener && window.opener.opener && window.opener.opener.top.mm_baseUrl)
                baseUrl = window.opener.opener.top.mm_baseUrl;
        }
        catch (e) { }

        var init = {
            mm_baseUrl: baseUrl
        }        

        var returnVal = window.showModalDialog(url, init, 'dialogWidth: ' + width + 'px; dialogHeight: ' + height + 'px;resizable: no; help: no; status: no; scroll: no');

        if (returnVal && returnVal.ok) {
            if (returnVal.objectName) {
                document.getElementById(displayfield).value = returnVal.objectName;
            }
            if (returnVal.objectId) {
                document.getElementById(idfield).value = returnVal.objectId;
            }
        }        
    }
}

function ConditionalRequiredValidator(useOrCriteria, forGroup, forProperty) {
    this.orCriteria = useOrCriteria;
    this.group = (forGroup) ? forGroup : '';
    this.property = forProperty;

    this.conditions = new Array();
}

ConditionalRequiredValidator.prototype.addBinaryCondition = function(propertyName, value, operator) {
    this.conditions.push(new BinaryCondition(this, propertyName, value, operator));
}

ConditionalRequiredValidator.prototype.addInCondition = function(propertyName, values) {
    this.conditions.push(new InCondition(this, propertyName, values));
}

ConditionalRequiredValidator.prototype.addNullCondition = function(propertyName) {
    this.conditions.push(new NullCondition(this, propertyName));
}

ConditionalRequiredValidator.prototype.addBetweenCondition = function(propertyName, minValue, maxValue) {
    this.conditions.push(new BetweenCondition(this, propertyName, minValue, maxValue));
}

ConditionalRequiredValidator.prototype.validate = function(value) {
    if (this.isVisible()) {
        if (this.canValidate()) {
            return ((value) && (value.length > 0));
        }
        return false;
    }
    return true;
}

ConditionalRequiredValidator.prototype.canValidate = function() {
    var valid = false;
    for (var v = 0; v < this.conditions.length; v++) {
        if (this.conditions[v].validate()) {
            valid = true;
            if (this.orCriteria) {
                break;
            }
        }
        else {
            valid = false;
            if (!this.orCriteria) {
                break;
            }
        }
    }
    return valid;
}

ConditionalRequiredValidator.prototype.evaluate = function() {
    if (this.canValidate()) {
        this.show();
    }
    else {
        this.hide();
    }
}

ConditionalRequiredValidator.prototype.findPropertyPanel = function() {
    var divs = document.getElementsByTagName('DIV');
    for(var i=0; i<divs.length; i++)
    {
        if (
                ((this.group.length == 0) || (divs[i].getAttribute('group') == this.group) )
                &&
                (divs[i].getAttribute('propertyName') == this.property) 
            )
        {
            return divs[i];
        }
    }

    var rows = document.getElementsByTagName('TR');
    for (var i = 0; i < rows.length; i++) {
        if (
                ((this.group.length == 0) || (rows[i].getAttribute('group') == this.group))
                &&
                (rows[i].getAttribute('propertyName') == this.property)
            ) {
            return rows[i];
        }
    }    
    
    return null;
}

ConditionalRequiredValidator.prototype.isVisible = function() {
    var pnl = this.findPropertyPanel();
    return ((pnl) && (pnl.style.display == 'block'));
}

ConditionalRequiredValidator.prototype.hide = function() {
    var pnl = this.findPropertyPanel();
    if (pnl) {
        pnl.style.display = 'none';
    }
}

ConditionalRequiredValidator.prototype.show = function() {
    var pnl = this.findPropertyPanel();
    if (pnl) {
        pnl.style.display = 'block';
    }
}

function BinaryCondition(validator, propertyName, value, operator) {
    this.owner = validator;
    this.wantedValue = value;
    this.property = propertyName;
    this.operatorType = operator;

    attachValueChange(this.owner.group, this.property, this.evaluate.bind(this));
}

BinaryCondition.prototype.evaluate = function() {
    this.owner.evaluate();
}

BinaryCondition.prototype.validate = function() {
    var val = getPropertyValue(this.owner.group, this.property);
    if (this.operatorType == 'LIKE') {
        return val.toLowerCase().indexOf(this.wantedValue.toLowerCase()) >= 0;
    }
    else {
        var expression = '' + val + '' + this.operatorType + '' + this.wantedValue + '';
        return eval(expression.toLowerCase())
    }
}

function BetweenCondition(validator, propertyName, minValue, maxValue) {
    this.owner = validator;
    this.wantedMinValue = minValue;
    this.wantedMaxValue = maxValue;
    this.property = propertyName;

    attachValueChange(this.owner.group, this.property, this.evaluate.bind(this));
}

BetweenCondition.prototype.evaluate = function() {
    this.owner.evaluate();
}

BetweenCondition.prototype.validate = function() {
    var val = getPropertyValue(this.owner.group, this.property);    
    var expression = '((' + val + ' >= ' + this.wantedMinValue + ') && (' + val + ' <= ' + this.wantedMaxValue + '))';
    return eval(expression.toLocaleLowerCase());
}


function NullCondition(validator, propertyName) {
    this.owner = validator;
    this.property = propertyName;
    attachValueChange(this.owner.group, this.property, this.evaluate.bind(this));
}

NullCondition.prototype.evaluate = function() {
    this.owner.evaluate();
}

NullCondition.prototype.validate = function() {
    var val = getPropertyValue(this.owner.group, this.property);
    return (val.length == 0);   
}

function InCondition(validator, propertyName, values) {
    this.owner = validator;
    this.allowedValues = values;
    this.property = propertyName;
    this.operatorType = operator;

    attachValueChange(this.owner.group, this.property, this.evaluate.bind(this));
}

InCondition.prototype.evaluate = function() {
    this.owner.evaluate();
}

InCondition.prototype.validate = function() {
    var val = getPropertyValue(this.owner.group, this.property);
    
    for(var i=0; i<this.allowedValues.length; i++)
    {    
        var expression = '' + val + ' == ' + this.allowedValues[i] + '';
        if(eval(expression.toLowerCase()))
        {
            return true;
        }
    }
    return false;
}

function getPropertyValue(group, property) {

    var value = '';
    var divs = document.getElementsByTagName('DIV');       
    var rows = document.getElementsByTagName('TR');

    value += getPropertyValues(group, property, divs);
    if (value.length > 0) {
        value += ' ';
    }
    value += getPropertyValues(group, property, rows);

    return value;
}

function getPropertyValues(group, property, holders) {
    var value = '';
    for (var i = 0; i < holders.length; i++) {
        if (
            (holders[i].getAttribute('propertyName') == property)
            &&
            ((group.length == 0) || (holders[i].getAttribute('group') == group))
            ) {
            var selects = holders[i].getElementsByTagName('SELECT');
            for (var f = 0; f < selects.length; f++) {
                if (value.length > 0) {
                    value += ' ';
                }
                value += selects[f].value;
            }

            var inputs = holders[i].getElementsByTagName('INPUT');
            for (var f = 0; f < inputs.length; f++) {
                if (value.length > 0) {
                    value += ' ';
                }

                if (inputs[f].type.toLowerCase() == 'checkbox') {
                    value += (inputs[f].checked) ? 'true' : 'false';
                }
                else {
                    value += inputs[f].value;
                }
            }
        }
    }
    return value;
}
function attachValueChange(group, property, eventTarget) {
    attachValueChanges(group, property, eventTarget, document.getElementsByTagName('DIV'));
    attachValueChanges(group, property, eventTarget, document.getElementsByTagName('TR'));
}


function attachValueChanges(group, property, eventTarget, holders) {
    for (var i = 0; i < holders.length; i++) {
        if (
            (holders[i].getAttribute('propertyName') == property)
            &&
            ((group.length == 0) || (holders[i].getAttribute('group') == group))
            ) {
            var selects = holders[i].getElementsByTagName('SELECT');
            for (var f = 0; f < selects.length; f++) {
                addListener(selects[f], 'change', eventTarget);
            }

            var inputs = holders[i].getElementsByTagName('INPUT');
            for (var f = 0; f < inputs.length; f++) {
                addListener(inputs[f], 'propertychange', eventTarget);
            }
        }
    }
}