var denodo = window.denodo || {};
//denodo.utils = denodo.utils || {};

denodo.utils = {
    popup: function (url,width,height) {
        newWindow = window.open(url,'name','height='+height+',width='+width);
        if (window.focus) {
            newWindow.focus()
        }
        return false;
    }
}

denodo.utils.cookies =
{
  /* METHOD: get();
   * PURPOSE: Get the value of a cookie
   * ARGUMENTS: STRING - cookieName - The name of the cookie value you wish to retrieve
   * RETURN: If cookie exists - STRING - the cookie value
   *         If cookie does not exist - null
   */
  get: function(cookieName)
  {
    var cookieNameStart,valueStart,valueEnd,cookieValue,returnValue;
    cookieNameStart = document.cookie.indexOf(cookieName+'=');
    if (cookieNameStart < 0)
    {
      returnValue = null;
    }
    else
    {
      valueStart = document.cookie.indexOf(cookieName+'=') + cookieName.length + 1;
      valueEnd = document.cookie.indexOf(";",valueStart);
      if (valueEnd == -1)
      {
        valueEnd = document.cookie.length;
      }
      cookieValue = document.cookie.substring(valueStart,valueEnd );
      returnValue = (cookieValue == '') ? null : unescape(cookieValue);
    }
    return returnValue;
  },
  /* METHOD: set();
   * PURPOSE: Write (or overwrite) a cookie (with supplemental information such as expiration, path, domain)
   * ARGUMENTS: cookieName - STRING - The name of the cookie value you wish to write
   *            value - STRING - The string you wish to write as the value of the cookie
   *            hoursToLive - INT/FLOAT - The number of hours until the cookie will expire.  If you do not provide
   *                                      this argument, or provide anything that can evaluate to false, or provide
   *                                      anything that can not be interpreted as a number, the expiration field for
   *                                      the cookie will not be set causing it to be deleted the next time the
   *                                      browser is closed (IE referes to this sort of cookie as a 'session' cookie).
   *            path - STRING - (Optional) The path for which the cookie is valid.  Defaults to "/" if not
   *                             passed, or passed empty.
   *            domain - STRING - (Optional) The domain for which the cookie is valid.  Defaults to
   *                              window.location.hostname if not passed, or passed empty.
   *            secure - BOOL - (Optional) This is used to instruct the browser to use SSL when sending the
   *                            cookie to a server.  It is almost never used, and will thus be assumed false
   *                            unless you explicitly pass true.
   * RETURN: VOID
   */
  set: function(cookieName,value,hoursToLive,path,domain,secure)
  {
    var expireString,timerObj,expireAt,pathString,domainString,secureString;
    //If no hoursToLive argument, or it is not numeric, do not set expiration
    if (!hoursToLive || typeof hoursToLive != 'number')
    {
      expireString = '';
    }
    else
    {
      timerObj = new Date();
      timerObj.setTime(timerObj.getTime()+(hoursToLive*60*60*1000));
      expireAt = timerObj.toGMTString();
      expireString = '; expires='+expireAt;
    }
    //If no path argument, or argument is empty string, set path to default of /
    path = (!path || path=='' || path==null) ? '/' : path;
    pathString = '; path='+path;
    //If no domain argument, or argument is empty string, set domain to default of window.location.hostname
    domain = (!domain || domain=='' || domain==null) ? window.location.hostname : domain;
    domainString = '; domain='+domain;
    //If secure argument is the BOOL true, set SSL string accordingly.  Otherwise, do not set it.
    secureString = (secure === true) ? '; secure' : '';
    //escape the value for HTTP transport to server
    value = escape(value);
    //Write the value to the document.cookie string
    document.cookie = cookieName+'='+value+expireString+pathString+domainString;
  },
  /* METHOD: del();
   * PURPOSE: Delete a cookie
   * ARGUMENTS: STRING - cookieName - The name of the cookie value you wish to delete
   *            path - STRING - (Optional) The path for which the cookie was set.  This is necessary if
   *                            the cookie was set with a particular path--you need to delete it with the
   *                            same.  Defaults to "/" if not passed, or passed empty.
   *            domain - STRING - (Optional) The domain for which the cookie was set.  This is necessary if
   *                            the cookie was set with a particular domain--you need to delete it with the
   *                            same.  Defaults to window.location.hostname if not passed, or passed empty.
   * RETURN: VOID
   */
  del: function(cookieName,path,domain)
  {
    path = (!path || !path.length) ? '' : path;
    domain = (!domain || !domain.length) ? '' : domain;
    jimAuld.utils.cookies.set(cookieName,'',-8760,path,domain);
  },
  /* METHOD: test();
   * PURPOSE: Test for cookie acceptance
   * ARGUMENTS: VOID
   * RETURN: If cookies accepted: BOOL - True
   *         If cookies not accepted: BOOL - False
   */
  test: function()
  {
    var returnValue;
    jimAuld.utils.cookies.set('cT','acc');
    var runTest = jimAuld.utils.cookies.get('cT');
    if (runTest == 'acc')
    {
      jimAuld.utils.cookies.del('cT');
      returnValue = true;
    }
    else
    {
      returnValue = false;
    }
    return returnValue;
  }
};


//Preparing namespace
var denodo = window.denodo || {};
denodo.utils = denodo.utils || {};
denodo.utils.url = denodo.utils.url || {};
denodo.utils.url.parsing = {
    getParameter: function(name) {
        //name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null) {
            return "";
        } else {
            return results[1];
        }
    }
};


/*SalesForce*/

var _kd = document;
var _kdlh = _kd.location.href;
var _ki,_kq,_kv;
var _kwtlForm;
var _kretURL;
var _kwtlOnSubmit;

function __krand() {
    return Math.round(Math.random() * 256).toString(16) + Math.round(Math.random() * 256).toString(16);
}

function __kuuid() {
    return __krand() + "-" + __krand() + "-" + __krand() + "-" + __krand() + new Date().getTime().toString(16);
}

function __kinit() {
    var q;
    var d = __kgetCookieDomain();
    var hasTrackingInfo = _kdlh.indexOf('&_kt=') != -1 || _kdlh.indexOf('?_kt=') != -1 ;
    if( _kd.cookie.indexOf('__kti') == -1 || hasTrackingInfo ) {
        _kv = new Date().getTime() + ',' + encodeURIComponent(_kdlh) + ',' + encodeURIComponent(_kd.referrer);
        _kd.cookie = "__kti=" + _kv + "; path=/; expires=Sun, 18 Jan 2038 00:00:00 GMT;" + (d==null ? "" : " domain="+d)
    }

    if( _kd.cookie.indexOf('__kts') == -1 || hasTrackingInfo ) {
        _kv = new Date().getTime() + ',' + encodeURIComponent(_kdlh) + ',' + encodeURIComponent(_kd.referrer);
        _kd.cookie = "__kts=" + _kv + "; path=/;" + (d==null ? "" : " domain="+d)
        q = "/" + encodeURIComponent(_kd.referrer);
    }

    if( _kd.cookie.indexOf('__ktv') == -1 ) {
        _kd.cookie = "__ktv=" + __kuuid() + "; path=/; expires=Sun, 18 Jan 2038 00:00:00 GMT;" + (d==null ? "" : " domain="+d)
    }

    if( _kd.cookie.indexOf('__ktt') == -1 ) {
        _kd.cookie = "__ktt=" + __kuuid() + "; path=/;" + (d==null ? "" : " domain="+d)
    }
}

function __kgetCookieDomain() {
    // top level domain suffixes that are usually found immediately after the domain name (e.g. www.google.co.uk)
    var domainSuffixes = "aero;arpa;biz;cat;co;coop;com;edu;gov;info;int;jobs;mil;mobi;museum;name;net;org;pro;travel;";
    var domain = document.domain;
    var temp = domain.split('.');
    if ( (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/).test(domain) ) {
        return domain;
    } else if ( temp.length == 1 ) {
        return null;
    } else {
        var d = "";
        var i = 0;
        while( i < 2 ) {
            i++;
            var suffix = temp[temp.length - i];
            d =  suffix + (i > 1 ? "." : "") + d;
            if ( domainSuffixes.indexOf(suffix + ";") != -1 ) {
                d = temp[temp.length - i - 1] + "." + d;
                break;
            }
        }
        return d;
    }
}

/**
 *  splits the cookie into its constituent pieces
 */
function __kvalueOf(name) {
    var cs = _kd.cookie.split(';');
    for( _ki = 0; _ki < cs.length; _ki++ ) {
        var index = cs[_ki].indexOf(name) ;
        if( index != -1 ) {
            _kv = cs[_ki].substring(index + 6);
            return _kv.split(',');
        }
    }

    return '';
}

function __koid(form, customForm) {
    return '00D70000000JCTD';
}

function __kpackValues(customForm) {
    var query  = '';
    var fields = _kwtlForm.elements;
    var regexp = /[0-9]/;
    for( var fieldIndex = 0; fieldIndex < fields.length; fieldIndex++ ) {
        var field = fields[fieldIndex];
        var name = field.getAttribute('name');

        // standard salesforce wtl
        if( name == 'debug' && field.value == '1' ) {
            // this is a debug page, leave it alone
            return true;

        } else if( name && !customForm && (regexp.exec(name) || "description" == name.toLocaleLowerCase()) ) {
            // ignore custom fields from standard

        } else if( name && ((name != 'retURL' && name != 'submit' && name != 'oid') || customForm) ) {
            if( field.value ) {
                var value = encodeURIComponent(field.value);
                query += encodeURIComponent(name) + '=' + value + '&';
            }
        }
    }
    return query;
}

function __kpackInfo(form, customForm) {
    var values = __kvalueOf('__kti=');
    var _ti = values[0] ? values[0] : '';
    var _li = values[1] ? values[1] : '';
    // landing page
    var _ri = values[2] ? values[2] : '';
    // referrer
    values = __kvalueOf('__kts=');
    var _ts = values[0] ? values[0] : '';
    var _ls = values[1] ? values[1] : '';
    // landing page
    var _rs = values[2] ? values[2] : '';

    var info = 't=' + _ti + '&r=' + _ri + '&l=' + _li + '&oid=' + __koid(form, customForm) + "&ts=" + _ts + "&ls=" + _ls + "&rs=" + _rs;
    info += '&url=' + _kurl();
    if( customForm ) {
        var method = typeof(form.method) == 'string' ? form.method : form.getAttribute('method');
        info += '&customForm=true&method='+ encodeURIComponent(method) + '&retURL=' + encodeURIComponent(__kgetAction(form)) ;
    } else if( _kretURL ) {
        info += '&customForm=false&retURL=' + encodeURIComponent(_kretURL.value);
    }

    return info;
}

function _kurl() {
    var url = _kdlh;
    var index = url.indexOf('?');
    if( index > 0 ) {
        url = url.substring(0, index);
    }
    return encodeURIComponent(url);
}

function __kgetSfgaField(form) {
    var fields = form.elements;
    for( var fieldIndex = 0; fieldIndex < fields.length; fieldIndex++ ) {
        var field = fields[fieldIndex];
        var name = field.getAttribute('name');

        if( name == 'sfga' ) {
            return field;
        }
    }

    return undefined;
}

function __kgetSFAction(form) {
    // referrer
    var url = 'http://lct.salesforce.com'
    if( _kdlh.toLowerCase().indexOf("https://") == 0 ) {
        url = 'https://lct.salesforce.com'
    }
    url += '/sfga';
    return url;
}

function __kgetAction(form) {
    return typeof(form.action) == 'string' ? form.action : form.getAttribute("action")
}

/**
 * submit form for processing
 */
function __konSubmit(event) {
    try {
        if( _kwtlOnSubmit && _kwtlOnSubmit(event) == false) { // very important that this is == false rather than !
            return false;
        }
    } catch ( error ) {}

    var url = __kgetSFAction(_kwtlForm);
    var customForm = false; // we know we're a standard wtl, so this is always false
    var values = __kpackValues(customForm);
    url += '?q=' + encodeURIComponent(values) + '&' + __kpackInfo(_kwtlForm, customForm);
    _kretURL.value = url;

    return true;
}

function __kfindWTL() {
    var forms = document.forms;
    for( var index = 0; index < forms.length; index++ ) {
        var form = forms[index];
        var action = form.getAttribute('action');
        if( action && action.indexOf && (action.indexOf('http://www.salesforce.com/servlet/servlet.WebToLead') != -1 || action.indexOf('https://www.salesforce.com/servlet/servlet.WebToLead') != -1) ) {
            for( var eIndex = 0; eIndex < form.length; eIndex++ ) {
                if( form.elements[eIndex].name == 'retURL' ) {
                    _kretURL = form.elements[eIndex];
                }
            }

            var customForm = false;
            /*
                Solo se ejecuta si el formulario es un WebToLead
                generado por SalesForce
            */
            __kSetupForm(form, customForm);
            break;
        }
    }



    /*
        Solo se ejecuta si el formulario no es de SalesForce
    */

    if( ! _kwtlForm ) {
        for( var i = 0; i < forms.length; i++ ) {
            var form = forms[i];
            for( var j = 0; j < form.elements.length; j++ ) {
                var input = form.elements[j];
                if( input.name == 'sfga' ) {
                    var customForm = true;
                    __kSetupForm(form, customForm);
                    break;
                }
            }
        }
    }
}

function __kSetupForm(form, customForm) {
    if( customForm ) {
        //Se ejecuta con nuestro formulario
        var sfga = __kgetSfgaField(form);
        sfga.value = __kpackInfo(form, customForm);
        form.setAttribute('action', __kgetSFAction(form));
    } else {
        _kwtlForm = form;
        if( form.onsubmit != undefined ) {
            var expr = "_kwtlOnSubmit = " + form.onsubmit.toString().replace(/this\s*([\)\.])/, '_kwtlForm$1');
            eval(expr);
        }
        form.onsubmit = __konSubmit;
    }
}

function salesforce() {
    __kinit();
}


function salesforce2() {
    __kinit();
    __kfindWTL();
}

if (denodo.utils.url.parsing.getParameter("[lL][sS]") != "") denodo.utils.cookies.set('ls',denodo.utils.url.parsing.getParameter("[lL][sS]"),24);

salesforce();

















