﻿function clickButton(event, buttonid) {
    var evt = event ? event : window.event;
    var button = document.getElementById(buttonid);
    if (button) {
        if (evt.keyCode == 13) {
            window.event.returnValue = false;
            if (evt.stopPropagation) evt.stopPropagation();
            if (evt.preventDefault) evt.preventDefault();
            switch (buttonid) {
                case "loginBTN":
                    AuthUser();
                    break;
                case "applyButton":
                    //                            button.focus();
                    if (document.getElementById("Invest")) {
                        document.getElementById("Invest").blur();
                    }
                    sendTradeOrder();
                    break;
                case "contactSubmitButton":
                    SendBriefContact();
                    break;
                default:
                    button.click();
                    break;
            }

            return false;
        }
    }
    return true
}

function changeLocation(url, target)
{
    switch(target)
    {
        case "opener":
            opener.location = url;
            window.close();
        break;
    }
}

function setClass(elm, className) {
    if (elm) {
        elm.setAttribute("class", className) || elm.setAttribute("className", className);
    }
}

function isLoggedIn() {
    if (isVarDefined("m_session") && m_session != "")
        return true;
    else
        return false;
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
    var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    return newnumber; // Output the result to the form field (change for your purposes)
}


function isVarDefined(str) {
    try {
        return (typeof eval(str) != 'undefined');
    }
    catch (e) {
        return false;
    }
}


function RandomNum(min, max) {
    var rand = Math.floor(Math.random() * (max - min + 1)) + min;
    return rand;
}



function onlyNumbers(evt) {
    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}


function XOR(a, b) {
    if ((a && !b) || (!a && b)) {
        return true;
    }
    else {
        return false;
    }
}
function isNumbers(evt) {
    var k = (evt.which) ? evt.which : event.keyCode;

    return ((k > 47 && k < 58) || k == 46 || k == 8);
}

function isEnglishOnly(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || (charCode == 8) || (charCode == 32))
        return true;

    return false;
}

function isEnglishNumbersOnly(evt) {
    if (isNumbers(evt))
        return true;
    return isEnglishOnly(evt);
}

function ShowMsgbox(Msg, CllBack) {
    title = getServerResource('CompanyTitle');
    jAlert(Msg, title, CllBack);
}

function BlinkControl(controlId) {
    var control = document.getElementById(controlId);
    if (control.style.visibility == "visible" || control.style.visibility == "")
        control.style.visibility = "hidden";
    else
        control.style.visibility = "visible";

}


function HTTPRequest(URL, Namespace, MethodName, Params, func) {
    var httpReq;
    var Host = document.location.host;
    var str = '<?xml version="1.0" encoding="utf-8"?>';
    str += '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">';
    str += '<soap:Body>';
    str += '<' + MethodName + ' xmlns="http://tempuri.org/' + Namespace + '">';
    if (Params != null) {
        for (var i = 0; i < Params.length; i += 2) {
            str += '<' + Params[i] + '>' + Params[i + 1] + '</' + Params[i] + '>';
        }
    }
    str += '</' + MethodName + '>';
    str += '</soap:Body>';
    str += '</soap:Envelope>';

    try {

        if (window.XMLHttpRequest) {
            httpReq = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            httpReq = new ActiveXObject("Msxml2.XMLHTTP");
        }
        if (!httpReq) {
            httpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }

        var fault;
        httpReq.open("POST", URL, (func != null));
        httpReq.setRequestHeader("POST", URL);
        httpReq.setRequestHeader("Host", Host);
        httpReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        httpReq.setRequestHeader("Content-Length", str.length);
        if (Namespace == '')
            httpReq.setRequestHeader("SOAPAction", "http://tempuri.org/" + MethodName);
        else
            httpReq.setRequestHeader("SOAPAction", "http://tempuri.org/" + Namespace + "/" + MethodName);

        if (func != null) {
            httpReq.onreadystatechange = function() {
                if (httpReq.readyState == 4) {
                    var Result = returnHTTPResult(httpReq, MethodName);

                    delete httpReq;
                    func(Result);
                }
            }
            httpReq.send(str);
        }
        else {
            httpReq.send(str);
            //var Dom = httpReq.responseXML;
            var Result = returnHTTPResult(httpReq, MethodName);
            delete httpReq;

            return Result;
        }
    }
    catch (ex) {
        debugger;
        //if (httpReq.responseText != null) alert(httpReq.responseText + " OR " + ex.message, "Error...");
    }
}

function returnHTTPResult(httpReq, methodName) {
    var Dom = httpReq.responseXML.documentElement;
    if (Dom == null) return null;
    var Result = Dom.getElementsByTagName(methodName + 'Result')

    if (Result == null) {
        debugger;
        fault = Dom.selectSingleNode("//faultstring");
        if (fault == null)
            alert(getServerResource("Utils_PleaseTryAgain"), getServerResource("Utils_SystemError"));
        return null;
    }
    else
        return Result[0];
}



var LCIDRegx = new RegExp('&lcid=[0-9]+');
function switchLanguage(switcToLang) {
    var loc = window.location.href.replace('#', '');
    loc = loc.replace('&lcid=1033', '');
    loc = loc.replace('&lcid=1031', '');
    loc = loc.replace('&lcid=3082', '');
    loc = loc.replace('&lcid=1049', '');
    loc = loc.replace(LCIDRegx, '');
    loc = loc.replace('&c=es', '');
    if (loc.indexOf('?') == -1)
        loc = loc + '?'

    loc = loc + '&lcid=' + switcToLang;

    location.href = loc;
}


function detectBrowser() {

    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        return ieversion;
    }
    else
        return "";
}


/******************************************************/
//StringBuilder
function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
}

StringBuilder.prototype.toString = function() {
    return this.strings.join("");
}
//StringBuilder
/******************************************************/


/*****************************************************/
/*********************date formatter******************/
var Imtech = Imtech || {};

Imtech.Utils = {
    date: {
        "1033": {
            monthsLong: ["January", "Febraury", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            daysLong: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
            daysShort: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
            patterns: {
                "d": "M/d/yyyy",
                "D": "dddd, MMMM dd, yyyy",
                "f": "dddd, MMMM dd, yyyy H:mm tt",
                "F": "dddd, MMMM dd, yyyy H:mm:ss tt",
                "g": "M/d/yyyy H:mm tt",
                "G": "M/d/yyyy H:mm:ss tt",
                "m": "MMMM dd",
                "o": "yyyy-MM-ddTHH:mm:ss.fff",
                "s": "yyyy-MM-ddTHH:mm:ss",
                "t": "H:mm tt",
                "T": "H:mm:ss tt",
                "U": "dddd, MMMM dd, yyyy HH:mm:ss tt",
                "y": "MMMM, yyyy"
            },
            tt: {
                "AM": "AM",
                "PM": "PM"
            },
            clockType: 24
        },
        "1043": {
            monthsLong: ["januari", "febrauri", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"],
            monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
            daysLong: ["maandag", "dinsdag", "woensdag", "donderdag", "vridag", "zaterdag", "zondag"],
            daysShort: ["ma", "di", "wo", "do", "vr", "za", "zo"],
            patterns: {
                "d": "d-M-yyyy",
                "D": "dddd d MMMM yyyy",
                "f": "dddd d MMMM yyyy H:mm",
                "F": "dddd d MMMM yyyy H:mm:ss",
                "g": "d-M-yyyy H:mm",
                "G": "d-M-yyyy H:mm:ss",
                "m": "dd MMMM",
                "o": "yyyy-MM-ddTHH:mm:ss.fff",
                "s": "yyyy-MM-ddTHH:mm:ss",
                "t": "H:mm",
                "T": "H:mm:ss",
                "U": "dddd d MMMM yyyy HH:mm:ss",
                "y": "MMMM, yyyy"
            },
            tt: {
                "AM": "",
                "PM": ""
            },
            clockType: 24
        }
    }
}


Date.prototype.formatTime = function(format, locale) {
    if (locale == null) locale = 1033;
    var fd = this.toString();
    var dateFormat = Imtech.Utils.date[locale];
    if (typeof (dateFormat) !== "undefined") {
        var pattern = typeof (dateFormat.patterns[format]) !== "undefined" ? dateFormat.patterns[format] : format;

        fd = pattern.replace(/yyyy/g, this.getFullYear());
        fd = fd.replace(/yy/g, (this.getFullYear() + "").substring(2));

        var month = this.getMonth();
        fd = fd.replace(/MMMM/g, dateFormat.monthsLong[month].escapeDateTimeTokens());
        fd = fd.replace(/MMM/g, dateFormat.monthsShort[month].escapeDateTimeTokens());
        fd = fd.replace(/MM/g, month + 1 < 10 ? "0" + (month + 1) : month + 1);
        fd = fd.replace(/(\\)?M/g, function($0, $1) { return $1 ? $0 : month + 1; });

        var dayOfWeek = this.getDay();
        fd = fd.replace(/dddd/g, dateFormat.daysLong[dayOfWeek].escapeDateTimeTokens());
        fd = fd.replace(/ddd/g, dateFormat.daysShort[dayOfWeek].escapeDateTimeTokens());

        var day = this.getDate();
        fd = fd.replace(/dd/g, day < 10 ? "0" + day : day);
        fd = fd.replace(/(\\)?d/g, function($0, $1) { return $1 ? $0 : day; });

        var hour = this.getHours();
        if (dateFormat.clockType == 12) {
            if (hour > 12) {
                hour -= 12;
            }
        }

        fd = fd.replace(/HH/g, hour < 10 ? "0" + hour : hour);
        fd = fd.replace(/(\\)?H/g, function($0, $1) { return $1 ? $0 : hour; });

        var minutes = this.getMinutes();
        fd = fd.replace(/mm/g, minutes < 10 ? "0" + minutes : minutes);
        fd = fd.replace(/(\\)?m/g, function($0, $1) { return $1 ? $0 : minutes; });

        var seconds = this.getSeconds();
        fd = fd.replace(/ss/g, seconds < 10 ? "0" + seconds : seconds);
        fd = fd.replace(/(\\)?s/g, function($0, $1) { return $1 ? $0 : seconds; });

        fd = fd.replace(/fff/g, this.getMilliseconds());

        fd = fd.replace(/tt/g, this.getHours() > 12 || this.getHours() == 0 ? dateFormat.tt["PM"] : dateFormat.tt["AM"]);
    }

    return fd.replace(/\\/g, "");
}

String.prototype.escapeDateTimeTokens = function() {
    return this.replace(/([dMyHmsft])/g, "\\$1");
}
/*****************************************************/
function clone(obj)
 { var clone = {};
   clone.prototype = obj.prototype;
   for (property in obj) clone[property] = obj[property];
   return clone;
}
function SelectOptionByValue(selectControlID, value) {
    var indexToSelect = 0;
    
    var selectobject = document.getElementById(selectControlID)
    for (var i = 0; i < selectobject.length; i++) {
        if (selectobject.options[i].value == value)
            indexToSelect = selectobject.options[i].index;
    }
    if (indexToSelect != 0)
        selectobject.selectedIndex = indexToSelect;
}


// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    var i = '';

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());
    // if the expires variable is set, make the correct expires time, the
    // current script below will set it for x number of days, to make it
    // for hours, delete * 24, for minutes, delete * 60 * 24
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    //alert( 'today ' + today.toGMTString() );// this is for testing purpose only
    var expires_date = new Date(today.getTime() + (expires));
    //alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function stringFormat(format, arguments) { 
    var str = format; 
    for (i = 0; i < arguments.length; i++) {
        str = str.replace('{' + i + '}', arguments[i]).replace('{' + i + '}', arguments[i]).replace('{' + i + '}', arguments[i]); 
    } 
    return str; 
}

function substructDates(date1, date2) {
    var timeZoneOffset = (new Date()).getTimezoneOffset() * 60 * 1000;

    return new Date((date1 - date2) + timeZoneOffset);
}

function msToTimeSpan(msTime) {
    var timeZoneOffset = (new Date()).getTimezoneOffset() * 60 * 1000;
    return new Date(msTime + timeZoneOffset);
}

function deleteTableRowElement(row) {
    row.parentNode.removeChild(row);
}
function RGBToHex(rgb)
{
    var red = parseInt(rgb.toString().split(",")[0].substr(4));
    var green = parseInt(rgb.toString().split(",")[1]);
    var blue =  parseInt(rgb.toString().split(",")[2]);
    var decColor =  red + 256 * green + 65536 * blue;
    if(decColor == 0)
    {
        return "#000000";
    }
    var revColor = decColor.toString(16).substr(4,2) + decColor.toString(16).substr(2,2) + decColor.toString(16).substr(0,2);
    return "#" + revColor;
}

String.prototype.endsWith = function(str) { return (this.match(str + "$") == str) }
String.prototype.startsWith = function(str) { return (this.match("^" + str) == str) }
String.prototype.trim = function() { return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) }


function evalHttpResponseText(result) {
    if (result == null)
        return (null);
    else if (typeof (result.textContent) == 'undefined') 
        return (eval(result.text));    
    else 
        return (eval(result.textContent));

}
/*****************************Time.js**********************************************/
function startClock() {
    setInterval("setTimeDisplay()", 1000);
}

function setTimeDisplay() {
    var clientTime = ServerTime.getInstance().GetServerTime();
    var currentTimeString = clientTime.formatTime("HH:mm:ss");
    document.getElementById("clock").innerHTML = currentTimeString;
}
var ServerTime = (function() {
    var instance = null;

    function InternalTime() {
        var m_timeDiff;



        this.GetServerTime = function() {
            var clientTime = new Date();
            clientTime.setTime(clientTime.getTime() + m_timeDiff);

            return clientTime;
        }

        this.setTimeDiff = function() {
            var params = new Array();
            params[0] = "clientTime";
            var d = new Date();
            params[1] = d.getTime() - (d.getTimezoneOffset() * 1000 * 60);

            var result = HTTPRequest("/Services/GeneralServices.asmx", "", "GetTimeDiff", params, null);
            if (typeof (result.textContent) == 'undefined')
            { m_timeDiff = eval(result.text); }
            else {
                m_timeDiff = eval(result.textContent);
            }
        }

        this.setTimeDiff();

    }

    return new function() {
        this.getInstance = function() {
            //            debugger;
            if (instance == null) {
                instance = new InternalTime();
                instance.constructor = null;
            }
            return instance;
        }
    }
})();

/*****************************Time.js**********************************************/