﻿/* 

(C) 2010 Global Teleworking SL
------------------------------

Funciones auxiliares usadas en otros archivos gtw.*.js

*/
/// <reference path="jquery-1.4.3-vsdoc.js" />

var steeldomusWebserviceUrl = '/samples/services/SteeldomusService.asmx/';
var PAYMENT_CC = 1;
var PAYMENT_TRANSFER = 2;
var PAYMENT_COD = 3;

//parámetros de la URL
var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();


//GetFilename: devuelve la parte del nombre (sin extensión) de una url. Ej: /sss/rrr/samples-fr.aspx --> samples-fr
function GetFilename(url) {
    if (url) {
        var m = url.toString().match(/.*\/(.+?)\./);
        if (m && m.length > 1) {
            return m[1];
        }
    }
    return "";
}

function isNumeric(string) {

    var numericExpression = /^[0-9]+$/;

    if (string.match(numericExpression)) {
        return true;
    } else {
        return false;
    }
}

//ActivarZoom: define eventos hover para zoom de los elementos img dentro de los elementos del param selector.
// Al pasar el mouse, el tamaño pasa de 30x30 a 75x75 y vuelve a 30x30
function ActivarZoom(selector) {
    $(selector).hover(function () {
        $(this).css({ 'z-index': '10' }); /*Add a higher z-index value so this image stays on top*/
        $(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
                            .animate({
                                marginTop: '-45px', /* The next 4 lines will vertically align this image */
                                marginLeft: '-45px',
                                top: '50%',
                                left: '50%',
                                width: '75px', /* Set new width */
                                height: '75px', /* Set new height */
                                padding: '0px'
                            }, 200); /* this value of "200" is the speed of how fast/slow this hover animates */

    }, function () {
        $(this).css({ 'z-index': '0' }); /* Set z-index back to 0 */
        $(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
                            .animate({
                                marginTop: '0', /* Set alignment back to default */
                                marginLeft: '0',
                                top: '0',
                                left: '0',
                                /*padding: '5px',*/
                                width: '30px', /* Set width back to default */
                                height: '30px' /* Set height back to default */
                            }, 400);
    });
}


// Array Remove - By John Resig (MIT Licensed)
Array.remove = function (array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

//Se llama desde el carrito (pags con masterpage SCart.Master) pasando el dir del idioma activo ('fr/', 'de/'...)
function sendQuestionsLang(lang) {
    
    lang = ObtenerDirDesdeIdioma(lang);
    
    var url = "http://www.steeldomus.com/" + lang + "/links_diversi/questions.htm";
    //var url = "http://www.steeldomus.com/forms/info.aspx";
    openwindow = window.open(url, "questions", "width=1100, height=680, left=0, top=0, titlebar=no, scrollbars=yes,resizable=yes");
    openwindow.focus();
}

//Se llama desde la solicitud de muestras (samples-xx.aspx), donde la var idioma está definida como 'XX' (gtw.samples.js)
function sendQuestions() {
    var lang = idioma.toLowerCase();
    sendQuestionsLang(lang);
}

function ObtenerDirDesdeIdioma(lang) {
    if (lang[lang.length - 1] == '/')
        lang = lang.substr(0, lang.length - 1);
    if (lang == "de")
        lang = "d";
    return lang;
}

function escapeText(txt) {
    if (txt == null)
        return "";
    return $('<div/>').text(txt).html();
}

//devuelve el CartDTO con toda la info del carrito activo
function ObtenerInfoCarrito() {
    var info = null;
    $.ajax({
        type: 'POST',
        url: steeldomusWebserviceUrl + 'ObtenerInfoCarrito',
        contentType: 'application/json',
        dataType: 'json',
        timeout: 3000,
        async: false,
        success: function (data) {
            info = data.d;            
        },
        error: function (request, status, error) {
            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
        }
    });
    return info;
}

//Devuelve un CartItemDTO --> no necesario, usar CartDTO.CartItems devuelto por ObtenerInfoCarrito
//function ObtenerDeCarrito(cartItemIndex) {
//    var p = null;
//    $.ajax({
//        type: 'POST',
//        url: steeldomusWebserviceUrl + 'ObtenerArticuloCarrito',
//        contentType: 'application/json',
//        dataType: 'json',
//        data: JSON.stringify({ "itemIndex": cartItemIndex }),
//        timeout: 3000,
//        async: false,
//        success: function (data) {
//            p = data.d;
//        },
//        error: function (request, status, error) {
//            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
//        }
//    });
//    return p;
//}

function EliminarItemCarrito(cartItemIndex) {
    var p = null;
    $.ajax({
        type: 'POST',
        url: steeldomusWebserviceUrl + 'EliminarItemCarrito',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({ "itemIndex": cartItemIndex }),
        timeout: 3000,
        async: false,
        success: function (data) {
            p = data.d;
        },
        error: function (request, status, error) {
            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
        }
    });
    return p;
}

function FormatoDinero(cantidad, moneda, signo, sinDecimales) {
    var result = '';
    if (moneda != null && moneda != '') {
        result = moneda + " ";
    }

    if (signo) {
        if (cantidad > 0) result += " + ";
    }
        
    var decimales = ((sinDecimales) ? 0 : 2);
    result += $.currency(cantidad, { s: ".", d: ",", c: decimales });
    
    return result;
}

var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

function isInt(str) {
    return (intRegex.test(str));
}

function isFloat(str) {
    return (floatRegex.test(str));
}

function CargarListaPaises(selectElements, lang, callback) {
    $.ajax({
        type: 'POST',
        url: steeldomusWebserviceUrl + 'ObtenerListaPaises',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({ "idioma": lang }),
        success: function (data) {

            $.each(data.d, function (index, elem) { //elem es un string de la forma "GB;United Kingdom"

                var valueText = elem.split(';');

                $.each(selectElements, function (index, select) { //para cada SELECT...

                    var options = $(select).attr('options');

                    options[options.length] = new Option(valueText[1], valueText[0]); //añade el OPTION

                });

            });

            if (callback != null)
                callback();

        },
        error: function (request, status, error) {
            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
        }
    });

}

/* validation functions */
function initSelects(selector) {
    $(selector).each(function () {
        $(this).change(function () {
            if ($(this).val() == 0) { //no hay valor seleccionado, texto color azul muy suave
                $(this).css({ color: '#96adc2' }); 
                if ($(this).hasClass('requiredField')) {
                    $(this).addClass('requiredFieldHightlighted');
                }
            }
            else { //tiene valor, poner texto en negro
                $(this).css({ color: '#335c85' });
                if ($(this).hasClass('requiredField')) {
                    $(this).removeClass('requiredFieldHightlighted');
                }
                $('.qtip').qtip('destroy');
            }
        });
    });
}

function initElements(selector) {

    $(selector).each(function () {
        var defvalue = this.value;

        $(this).attr('title', defvalue);

        $(this).focus(function () { //al recibir el foco...
            if (this.value == defvalue) { //si aún no ha introducido nada, borra fondo y texto negro
                this.value = "";
                $(this).css({ color: '#335c85' });
                if ($(this).hasClass('requiredField')) {
                    $(this).removeClass('requiredFieldHightlighted');
                }
            }
            else { //ya tiene contenido, aunque sea ''
                $('.qtip').qtip('destroy');
            }
        });

        $(this).blur(function () { //al perder el foco...
            if ($.trim(this.value) == "") { //si está vacío
                this.value = defvalue; //pone el txt por defecto
                $(this).css({ color: '#96adc2' }); //color azul claro
                if ($(this).hasClass('requiredField')) { //y fondo amarillo si es obligatorio
                    $(this).addClass('requiredFieldHightlighted');
                }
            }
            else { //no vacío
                $(this).css({ color: '#335c85' }); //texto negro
                if ($(this).hasClass('requiredField')) { //y fondo normal si es oblig.
                    $(this).removeClass('requiredFieldHightlighted');
                }
                $('.qtip').qtip('destroy'); //desactivamos el qtip
            }
        });

//        $(this).change(function () {
//            if ($.trim(this.value) == "" || $.trim(this.value) == defvalue) {
//                $(this).css({ color: '#96adc2' });
//            }
//            else {
//                $(this).css({ color: '#335c85' });
//            }
//        });

    });
}

function requiredOK(elements, requiredMsg) {
    var ok = true;
    elements.each(function () {
        var element = $(this);
        if ((element.val() == element.attr('title')) || (element.val() == "") || (element.val() == 0)) {
            ShowTip(element.attr('id'), requiredMsg);
            ok = false;
            return false;
        }
    });
    return ok;
}

function MarcarObligatorios(elements) {
    elements.each(function () {
        $(this).addClass('requiredField');
    });
}

function ComprobarObligatorios(elementsSelector) {
    var ok = true;
    $(elementsSelector).each(function () {
        var element = $(this);
        if (element.hasClass('requiredField')) {
            if ((element.val() == element.attr('title')) || (element.val() == "") || (element.val() == 0)) {
                element.addClass('requiredFieldHightlighted');
                ok = false;
            }
            else {
                element.removeClass('requiredFieldHightlighted');
            }
        }
    });
    return ok;
}

function ShowTip(idElement, text) {
    $("#" + idElement).qtip({
        content: text,
        position: {
            my: 'bottom center',
            at: 'top center'
        },
        style: {
            tip: "bottomCenter"
        },
        show: {
            ready: true
        },
        hide: {
            event: false,
            inactive: 0
        }
    });
}

function ShowTipGeneral(idElement, text) {
    $("#" + idElement).qtip({
        content: text,
        position: {
            my: 'bottom center',
            at: 'top center'
        },
        show: {
            ready: true
        },
        style: {
            tip: {
                corner: false
            }
        },
        hide: {
            event: false,
            inactive: 0
        }
    });
}

//Devuelve true si se pasa una dir de email válida
function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\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,}))$/
    return email.match(re);
}

// BOI, followed by one digit, followed by EOI.
var reDigit = /^\d/

// Returns true if character c is a digit 
// (0 .. 9).

function isDigit (c) {   
    return reDigit.test(c)
}

/*  ================================================================
Credit card verification functions
================================================================ */


/*  ================================================================
FUNCTION:  isCreditCard(st)
 
INPUT:     st - a string representing a credit card number

RETURNS:  true, if the credit card number passes the Luhn Mod-10 
          test. false, otherwise
================================================================ */

function isCreditCard(st) {
    // Encoding only works on cards with less than 19 digits
    if (st.length > 19)
        return (false);

    sum = 0; mul = 1; l = st.length;
    for (i = 0; i < l; i++) {
        digit = st.substring(l - i - 1, l - i);
        tproduct = parseInt(digit, 10) * mul;
        if (tproduct >= 10)
            sum += (tproduct % 10) + 1;
        else
            sum += tproduct;
        if (mul == 1)
            mul++;
        else
            mul--;
    }
    
    if ((sum % 10) == 0)
        return (true);
    else
        return (false);

} // END FUNCTION isCreditCard()



/*  ================================================================
FUNCTION:  isVisa()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid VISA number.
            
false, otherwise

Sample number: 4111 1111 1111 1111 (16 digits)
================================================================ */

function isVisa(cc) {
    if (((cc.length == 16) || (cc.length == 13)) &&
      (cc.substring(0, 1) == 4))
        return isCreditCard(cc);
    return false;
}  // END FUNCTION isVisa()




/*  ================================================================
FUNCTION:  isMasterCard()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid MasterCard
number.
            
false, otherwise

Sample number: 5500 0000 0000 0004 (16 digits)
================================================================ */

function isMasterCard(cc) {
    firstdig = cc.substring(0, 1);
    seconddig = cc.substring(1, 2);
    if ((cc.length == 16) && (firstdig == 5) &&
      ((seconddig >= 1) && (seconddig <= 5)))
        return isCreditCard(cc);
    return false;

} // END FUNCTION isMasterCard()





/*  ================================================================
FUNCTION:  isAmericanExpress()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid American
Express number.
            
false, otherwise

Sample number: 340000000000009 (15 digits)
================================================================ */

function isAmericanExpress(cc) {
    firstdig = cc.substring(0, 1);
    seconddig = cc.substring(1, 2);
    if ((cc.length == 15) && (firstdig == 3) &&
      ((seconddig == 4) || (seconddig == 7)))
        return isCreditCard(cc);
    return false;

} // END FUNCTION isAmericanExpress()




/*  ================================================================
FUNCTION:  isDinersClub()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid Diner's
Club number.
            
false, otherwise

Sample number: 30000000000004 (14 digits)
================================================================ */

function isDinersClub(cc) {
    firstdig = cc.substring(0, 1);
    seconddig = cc.substring(1, 2);
    if ((cc.length == 14) && (firstdig == 3) &&
      ((seconddig == 0) || (seconddig == 6) || (seconddig == 8)))
        return isCreditCard(cc);
    return false;
}



/*  ================================================================
FUNCTION:  isCarteBlanche()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid Carte
Blanche number.
            
false, otherwise
================================================================ */

function isCarteBlanche(cc) {
    return isDinersClub(cc);
}




/*  ================================================================
FUNCTION:  isDiscover()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid Discover
card number.
            
false, otherwise

Sample number: 6011000000000004 (16 digits)
================================================================ */

function isDiscover(cc) {
    first4digs = cc.substring(0, 4);
    if ((cc.length == 16) && (first4digs == "6011"))
        return isCreditCard(cc);
    return false;

} // END FUNCTION isDiscover()





/*  ================================================================
FUNCTION:  isEnRoute()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid enRoute
card number.
            
false, otherwise

Sample number: 201400000000009 (15 digits)
================================================================ */

function isEnRoute(cc) {
    first4digs = cc.substring(0, 4);
    if ((cc.length == 15) &&
      ((first4digs == "2014") ||
       (first4digs == "2149")))
        return isCreditCard(cc);
    return false;
}



/*  ================================================================
FUNCTION:  isJCB()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is a valid JCB
card number.
            
false, otherwise
================================================================ */

function isJCB(cc) {
    first4digs = cc.substring(0, 4);
    if ((cc.length == 16) &&
      ((first4digs == "3088") ||
       (first4digs == "3096") ||
       (first4digs == "3112") ||
       (first4digs == "3158") ||
       (first4digs == "3337") ||
       (first4digs == "3528")))
        return isCreditCard(cc);
    return false;

} // END FUNCTION isJCB()



/*  ================================================================
FUNCTION:  isAnyCard()
 
INPUT:     cc - a string representing a credit card number

RETURNS:  true, if the credit card number is any valid credit
card number for any of the accepted card types.
            
false, otherwise
================================================================ */

function isAnyCard(cc) {
    if (!isCreditCard(cc))
        return false;
    if (!isMasterCard(cc) && !isVisa(cc) && !isAmericanExpress(cc) && !isDinersClub(cc) &&
      !isDiscover(cc) && !isEnRoute(cc) && !isJCB(cc)) {
        return false;
    }
    return true;

} // END FUNCTION isAnyCard()


//==================================================================================================================================
// FORMULARIOS WEB: solicitud de info, solicitud de call-me y solicitud de muestras
// Se llaman desde las pag del carrito (SCart.Master), los forms (Forms.Master) y las páginas generadas. 
// Si no existe una var 'idioma' (definida en los forms y en la de cfg del carrito), la toma del carrito

function FormSendQuestions(language) {
    var lang = "EN";
    if (typeof idioma === 'undefined') {
        var info = ObtenerInfoCarrito();
        if (info == null || info.Language == "Undefined")
            lang = language;
        else
            lang = info.Language;
    }
    else
        lang = idioma;
    var url = "/forms/inforeq.aspx?lang=" + lang;
    openwindow = window.open(url, "info", "width=950, height=900, left=0, top=0, titlebar=no, scrollbars=yes,resizable=yes");
    openwindow.focus();
}

function FormCallMe(language) {

    var lang = "EN";
    if (typeof idioma === 'undefined') {
        var info = ObtenerInfoCarrito();
        if (info == null || info.Language == "Undefined")
            lang = language;
        else
            lang = info.Language;
    }
    else
        lang = idioma;
    var url = "/forms/callme.aspx?lang=" + lang;
    openwindow = window.open(url, "callme", "width=950, height=900, left=0, top=0, titlebar=no, scrollbars=yes,resizable=yes");
    openwindow.focus();
}

function FormRequestSamples(art) {
    var lang = "EN";
    if (typeof idioma === 'undefined') {
        var info = ObtenerInfoCarrito();
        lang = (info != null && info.Language != undefined ? info.Language : "EN");
    }
    else
        lang = idioma;
    var url = "/samples/samples.aspx?art=" + art + "&lang=" + lang;
    openwindow = window.open(url, "samplesRequest", "width=950, height=940, left=0, top=0, titlebar=no, scrollbars=yes,resizable=yes");
    openwindow.focus();
}

//=================================================//

// Devuelve precio del producto
// Llamada síncrona al webservice.
function ObtenerPrecioProducto(productCode, idioma) {
    var p = null;
    $.ajax({
        type: 'POST',
        url: steeldomusWebserviceUrl + 'ObtenerPrecioProducto',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({ "codigo": productCode, "idioma": idioma }),
        timeout: 3000,
        async: false,
        success: function (data) {
            p = data.d;
        },
        error: function (request, status, error) {
            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
        }
    });
    return p;
}

// Comprueba si el producto codigo tiene muestras que se pueden solicitar, y si las tiene, llama a la callback. 
// Llamada asíncrona al webservice.
function CheckMuestrasDisponibles(codigo, callbackSiTiene) {
    $.ajax({
        type: 'POST',
        url: steeldomusWebserviceUrl + 'TieneMuestrasDisponibles',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({ "codigo": codigo }),
        timeout: 3000,
        success: function (data) {
            var tiene = data.d;
            if (tiene)
                callbackSiTiene();
        },
        error: function (request, status, error) {
            alert("Database not available at the moment. Please try again later. Status: " + status); //request.responseText);
        }
    });
}

