//Definimos los namespaces
Type.registerNamespace('Devy');


//Clase con metodos utiles estaticos
Devy.Util = function () { }

Devy.Util.OpenPopup = function (url, width, height) {
    if (width === undefined) width = 750;
    if (height === undefined) height = 550;

    var options = 'height=' + height + ',width=' + width;

    newwindow = window.open(url, 'DevyPopUp', options);
    if (window.focus) { newwindow.focus(); }
}

Devy.Util.OpenURL = function (url) {
    window.location =url;
}


Devy.Util.Meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

Devy.Util.SetDatePicker = function (input) {
    setTimeout(function () {
        $(input).datepicker({
            dateFormat: 'dd/mm/yy',
            showAnim: 'slideDown', duration: 'fast',
            changeMonth: true,
            changeYear: true,
            dayNamesMin: ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'],
            dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
            monthNames: Devy.Util.Meses,
            monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']
        });
    }, 1000);
}

Devy.Util.SetNumericTextBox = function (input) {
    $(input).numeric();
}
/*GET VALUE*/
Devy.Util.GetFormFieldValue = function (input, DataType) {
    switch (DataType) {
        case "Date":
            return Devy.Util.GetFormDateFieldValue(input);
            break;

        case "Boolean":
            return Devy.Util.GetFormBooleanFieldValue(input);
            break;

        case "Number":
            return Devy.Util.GetFormNumericFieldValue(input);
            break;

        default: //text
            return Devy.Util.GetFormTextFieldValue(input);
            break;
    }
}
Devy.Util.GetFormDateFieldValue = function (input) {
    try {
        var fecha = Date.parseLocale(Devy.Util.GetFormTextFieldValue(input));
        if (fecha == null) fecha = {};

        return fecha;
    }
    catch (e) {
        return {};
    }
}

Devy.Util.GetFormNumericFieldValue = function (input) {
    try {
        var strValue = Devy.Util.GetFormTextFieldValue(input);
        if (strValue)
            return parseFloat(strValue);
        else
            return 0;
    }
    catch (e) {
        return 0;
    }
}

Devy.Util.GetFormBooleanFieldValue = function (input) {
    if (input.checked)
        return true;
    else
        return false;
}

Devy.Util.GetFormTextFieldValue = function (input) {
    return input.value;
}
/*SET VALUE*/
Devy.Util.SetFormFieldValue = function (input, DataType, value) {
    switch (DataType) {
        case "Date":
            Devy.Util.SetFormDateFieldValue(input, value);
            break;

        case "Boolean":
            Devy.Util.SetFormBooleanFieldValue(input, value);
            break;

        case "Number":
            Devy.Util.SetFormNumericFieldValue(input, value);
            break;

        default: //text
            Devy.Util.SetFormTextFieldValue(input, value);
            break;
    }
}
Devy.Util.SetFormDateFieldValue = function (input, value) {
    try {
        if (value)
            input.value = value.localeFormat('d');
        else
            input.value = '';
    }
    catch (e) {
        input.value = '';
    }
}

Devy.Util.SetFormNumericFieldValue = function (input, value) {
    if (value !== undefined)
        input.value = value;
    else
        input.value = '';
}

Devy.Util.SetFormBooleanFieldValue = function (input, value) {
    if (value)
        $(input).attr("checked", "checked");
    else
        $(input).removeAttr("checked");
}



Devy.Util.SetFormTextFieldValue = function (input, value) {
    if (Devy.Util.GetObjectIsTextArea(input)) {
        Devy.Util.SetFormTextFieldValueDelayed(input, value);
    }
    else {
        if (value !== undefined) {
            $(input).val(value);
        }
        else {
            $(input).val('');
        }
    }
}

//FIX PARA FIREFOX EN TEXTAREAS... NO LE ENCONTRE OTRA VUELTA
Devy.Util.SetFormTextFieldValueDelayed = function (input, value) {
    setTimeout(function () {
        if (value !== undefined) {
            $(input).val(value);
        }
        else {
            $(input).val('');
        }
    }, 10);
}

Devy.Util.GetObjectIsTextArea = function (obj) {
    if (obj) {
        var objStr = obj.toString().toLowerCase();

        if (objStr.indexOf('htmltextareaelement') != -1)
            return true;
    }

    return false;
}

Devy.Util.HTMLEncode = function (value) {

    value = value.replace(/</g, '&lt;');
    value = value.replace(/>/g, '&gt;');

    value = value.replace(/\r\n/g, '<br />');
    value = value.replace(/\n/g, '<br />');

    return value;
}

Devy.Util.URLEncode = function (value) {
    var string = value.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return escape(utftext);
}


Devy.Util.ThumbNailURL = function (imageURL, width, height, cropType) {
    if (!height) height = 0;
    if (!cropType) cropType = 0;

    /*"/_devy/thumbnail.aspx?w={0}&h={1}&fn={2}&ct={3}&hc=1",*/
    return String.format("/_devy/thumbnails/w{0}_h{1}_hc1_e0_ct{2}_f{3}.jpg", 
     width, height, cropType, Devy.Util.URLEncode(imageURL));
}

Devy.Util.Clone = function (obj) {
    var tmp = Sys.Serialization.JavaScriptSerializer.serialize(obj);
    return Sys.Serialization.JavaScriptSerializer.deserialize(tmp);
}

Devy.Util.URLisLocal = function (url) {
    if (url) {
        return (url.indexOf("://") == -1)
    }
    else
        return false;
}

Devy.Util.RenderFlash = function (flashUrl, width, height) {
    var flashId = Math.ceil(Math.random() * 1000000);

    return '<object id="' + flashId + '_object" height="' + height + '" border="0" width="' + width + '" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">' +
                '<param value="' + flashUrl + '" name="movie"/>' +
                '<param value="autohigh" name="quality"/>' +
                '<param value="true" name="loop"/>' +
                '<param value="always" name="allowscriptaccess"/>' +
                '<param value="transparent" name="wmode"/>' +
                '<embed id="' + flashId + '_embed" height="' + height + '" border="0" width="' + width + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" wmode="transparent" allowscriptaccess="always" loop="true" quality="autohigh" src="' + flashUrl + '" name="' + flashId + '"/>' +
                '</object>';
}

Devy.Util.LeadingZeroes = function (number, totalLenght) {
    var sN = number.toString();
    var pad = '';
    for (var i = 0; i < (totalLenght - sN.length); i++) {
        pad += '0';
    }

    return pad + sN;
}


Devy.Util.StringTrim = function (string) {
    for (i = 0; i < string.length; ) {
        if (string.charAt(i) == " ")
            string = string.substring(i + 1, string.length);
        else
            break;
    }

    for (i = string.length - 1; i >= 0; i = string.length - 1) {
        if (string.charAt(i) == " ")
            string = string.substring(0, i);
        else
            break;
    }

    return string;
}

Devy.Util.SetCookie = function (cookieName, cookieValue, ExpireInDays) {
    var today = new Date();
    var expire = new Date();
    if (ExpireInDays == null || ExpireInDays == 0) ExpireInDays = 1;
    expire.setTime(today.getTime() + 3600000 * 24 * ExpireInDays);
    document.cookie = cookieName + "=" + escape(cookieValue)
                 + ";expires=" + expire.toGMTString();
}

Devy.Util.GetCookie = function (cookieName) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == cookieName) {
            return unescape(y);
        }
    }
} 

Devy.Util.ObjectAsFieldArray = function (obj) {
    var ret = new Array();

    if (obj) {
        for (var propName in obj) {
            Array.add(ret, { "Name": propName, "Value": obj[propName] });
        }
    }

    return ret;
}

Devy.Util.MapObject = function (source, target) {
    if (source) {
        for (var propName in source) {

            if (target["set_" + propName])
                target["set_" + propName](source[propName]);
            else
                target[propName] = source[propName];
        }
    }
}


Devy.Util.FacebookEventsOnCommentCreate = function (args) {
    Sys.Debug.traceDump(args, "FacebookComment");
}


Devy.Util.FormatNumberMiles = function (number) {
    if (isNaN(number)) number = 0;

    nStr = number.toFixed(2).toString();
    nStr = nStr.replace(",", ".");

    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;
}
