﻿//var monthNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") ;

function FormatDate (date, format)
{
    var formatSpec = {
        d    : IntToStr(date.getDate (), 1) ,
        dd   : IntToStr(date.getDate (), 2) ,
        MMM  : monthNames[date.getMonth ()] ,
        MM   : IntToStr(date.getMonth () + 1, 2) ,
        M    : IntToStr(date.getMonth () + 1, 1) ,
        yy   : IntToStr(date.getFullYear () % 100, 2) ,
        yyyy : IntToStr(date.getFullYear (), 4)
    };
    
    return format.replace(/d{1,2}|M{1,3}|(yy){1,2}/g, function ($0) { return formatSpec[$0] ; });
}

function ParseDate (date, format)
{
    var lastToken ;
    var value = "";
    var resdate = new Date () ;
    
    d = m = y = 0;
    for (var i = 0; i < format.length; ++i)
    {
        var fc = format.charAt (i) ;
        var dc = date.charAt (i) ;
        if (/[dMy]/.test(fc))
        {
            if (!isDigit (dc))
                return null ;
            if (lastToken != fc)
            {
                SetDate (resdate, lastToken, value) ;
                value = "" ;
                lastToken = fc ;
            }
            value += dc ;
        }
        else if (fc != dc)
            return null ;
    }
    SetDate (resdate, lastToken, value) ;
    return resdate ;
}

function isDigit (c)
{
    return /^\d$/.test(c) ;
}

function SetDate (date, field, value)
{
    if (field)
        switch (field)
        {
        case "d":
            date.setDate (parseInt (value)) ;
            return;
        case "M":
            date.setMonth (parseInt (value) - 1) ;
            return;
        case "y":
            date.setFullYear (parseInt (value)) ;
            return;
        }
}

function IntToStr (v, d)
{
    var res = v.toString () ;
    while (res.length < d)
        res = "0" + res ;
    return res ;
}

function ValidateForm (frm)
{
    var form = evalJson (frm) ;
    var valid = true ;
    for (var i = 0; i < form.length; ++i)
    {
        var item = form[i];
        valid = ValidateControl (item.Control, item.Error) && valid ;
    }
    return valid;
}

function ValidateControl (control, error)
{
    var value = control.GetValue () ;
    result = value != null && !/^\s*$/.test(value) ;
    SetErrorStatus (control, error, result) ;
    return result ;
}

function ValidateEmail (control, error)
{
    var result = ValidateControl (control, error) ;
    
    if (!result) return false ;
    
    var emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ;

    var matches = control.GetValue ().match (emailRegEx) ;
    result = matches != null ;

    if (result)
    {
        var domain = matches[5];

        var req = GetXmlHttpRequest() ;
        if (req)
        {
            req.open("GET", "/DomainCheck?Domain=" + domain, false) ;
            req.send(null) ;
            result = req.status == 200 ;
            if (!result)
            {
                Notification.ShowTimeout = 10000 ;
                Notification.Severity    = 3;
                Notification.Show ("Please use your company email address") ;
            }
        }
    }

    SetErrorStatus (control, error, result) ;
    return result ;
}

function SetErrorStatus(control, error, status)
{
    var errorMsg = error ? document.getElementById(error) : null ;
    if (status)
    {
        if (errorMsg)
            errorMsg.className = "Error Invisible" ;
    }
    else
    {
        if (errorMsg)
            errorMsg.className = "Error Visible" ;
        control.Focus () ;
    }
}

function ShowNewPanel (name, isVisible)
{
    document.getElementById("New" + name).className = isVisible ? "Visible" : "Invisible" ;
    document.getElementById("Existing" + name).className = isVisible ? "Invisible" : "Visible" ;
}

function SetVisibility (name, isVisibile)
{
    var el = document.getElementById (name) ;
    if (isVisibile)
        el.className = el.className.replace ("Invisible", "Visible") ;
    else
        el.className = el.className.replace ("Visible", "Invisible") ;

}

function GenericActionPaneCallbackCompleteHandler (s, e)
{
    ShowQuickPanelView ("") ;
    Notification.ShowTimeout = 10000 ;
    Notification.Show (e.result) ;
}

function GetXmlHttpRequest()
{
    req = null;
    if (window.XMLHttpRequest)
    {
        try
        {
            req = new XMLHttpRequest();
        }
        catch (e)
        { }
    }
    else if (window.ActiveXObject)
    {
        try
        {
            req = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch (e)
        {
            try
            {
                req = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch (e)
            { }
        }
    }
    
    return req ;
}

function evalJson (json)
{
    return eval ("(" + json.replace (/"\\\/Date\((\d+)([\+-]\d+)?\)\\\/"/g, "new Date($1)") + ")") ;
}

function ShowDropMenu (id)
{
    var item = document.getElementById ("menuitem_" + id) ;
    var menu = document.getElementById ("dropmenu_" + id) ;
    menu.className = "OpennedDropMenu" ;
    item.className = "OpennedDropMenu1" ;
}

function HideDropMenu (id, e)
{
/*
    // event bubling workaround
    // solution from http://www.quirksmode.org/js/events_mouse.html
    if (!e) var e = window.event;
	var tg = (window.event) ? e.srcElement : e.target;
	if (tg.nodeName != 'DIV') return;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	while (reltg != tg && reltg.nodeName != 'BODY')
		reltg = reltg.parentNode
	if (reltg == tg) return;
	// Mouseout took place when mouse actually left layer
	// Handle event
*/
    var item = document.getElementById ("menuitem_" + id) ;
    var menu = document.getElementById ("dropmenu_" + id) ;
    item.className = "ClosedDropMenu1" ;
    menu.className = "ClosedDropMenu" ;
}

function GetNumberEditorValue (editor)
{
    var point = editor.GetValue ().replace (/\d+/g, '') ;
    return parseFloat (editor.GetValue ().replace (point, '.')) ;
}

function SetNumberEditorValue (editor, value)
{
    var point = editor.GetValue ().replace (/\d+/g, '') ;
    var dec = editor.GetValue ().replace (new RegExp ("[^" + point + "]+\\" + point), '').length ;
    var padding = editor.GetValue ().toString ().length - value.toFixed (dec).toString ().length ;
    var val = value.toFixed (dec).toString ().replace ('.', point) ;
    while (padding-- > 0) val = "0" + val ;
    editor.SetValue (val) ;
}
