/** Depende de jQuery */

/*global alert,  escape, unescape, console, document, jQuery, window, $  */
/*jslint onevar: true, browser: true, devel: true, evil: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */

var cto = {
    popups : [],
    idSeed : 0,
    valid_email_RE: /^[a-z0-9!#$%&'*+\/=?\^_`{|}~\-]+(?:\.[a-z0-9!#$%&'*+\/=?\^_`{|}~\-]+)*@(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?$/i,
    bodyIframe : null,
     /**
      * Extraida de Ext JS. Crea el namespace
      */
    namespace : function () {
        var a = arguments, o = null, i, j, d, rt;
        for (i = 0; i < a.length; ++i) {
            d = a[i].split(".");
            rt = d[0];
            eval("if (typeof " + rt + " == \"undefined\") {" + rt + " = {};} o = " + rt + ";");
            for (j = 1; j < d.length; ++j) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }
    },
    /**
     * Funcion de log. Si esta firebug habilitado utiliza la consola. Sino hace
     * un alert de los parametros
     */
    log : function () {
        if (!cto.defaults.debug) { return; }
        if (window.console && window.console.firebug) {
            console.log(arguments);
        } else {
            alert(arguments);
        }
    },
    getCookieCuatro : function () {
        var cUser, idx_cookie, cookie, userNick;
        // posiciones en la cookie
        idx_cookie = {
            id : 0,
            nick : 1,
            mail : 3
        };
        cUser = null;
        cookie = $.cookie('cuatro_validation_info');
        if (cookie) {
            cookie = cookie.split('|');
            userNick = unescape(cookie[idx_cookie.nick]);
            userNick = userNick.replace("+", " ");
            userNick = userNick.replace("%2B", "+");
            userNick = userNick.replace("%2F", "/");
            if (userNick.length > 20) { userNick = userNick.substring(0, 17) + '...'; }
            cUser = {
                id : cookie[idx_cookie.id],
                nick : userNick,
                mail : cookie[idx_cookie.mail]
            };
        }
        return cUser;
    },
    id : function (el, prefix) {
        var t, id;
        prefix = prefix || "cto-gen-";
        t = el ? el = $(el) : true;
        id = prefix + (cto.idSeed += 1);
        return el ? (el.attr('id') ? el.attr('id') : el.attr('id', id).attr('id')) : id;
    },
    wrap : function (str) {
        return ('string' === typeof str) ? $(document.createElement('span')).html(str) : str;
    },
    
    /**
     * Transforma un queryString de formato texto a objeto. Ejemplo: var q =
     * cto.query('url/pagina.html?v1=aaa&v2=ccc'); q = {v1: 'aaa', v2: 'ccc' }
     * 
     */
    
    /*
     * Mantenido por compatibilidad. Usar cto.parseURL
     */
    query : function (s) {
        return cto.parseURL(s).params;
    },
    parseURL : function (url) {
        var a = document.createElement('a'), params = {}, seg, len, i = 0, s, RE;
        RE = {
            file: new RegExp("\/([^\/?#]+)$", 'i'),
            relative: new RegExp("tps?:\/\/[^\/]+(.+)")
        };
        a.href = url;
        seg = a.search.replace(/^\?/, '').split('&');
        len = seg.length;
        for (; i < len; i += 1) {
            if (!seg[i]) { continue; }
            s = seg[i].split('=');
            params[s[0]] = s[1];
        }
        return {
            source : url,
            protocol : a.protocol.replace(':', ''),
            host : a.hostname,
            port : a.port,
            query : a.search,
            params : params,
            file : (a.pathname.match(RE.file) || ['', ''])[1],
            hash : a.hash.replace('#', ''),
            path : a.pathname.replace(/^([^\/])/, '/$1'),
            relative : (a.href.match(RE.relative) || ['', ''])[1],
            segments : a.pathname.replace(/^\//, '').split('/')
        };
    },
    redirect : function (url) {
        window.location.href = url;
    },
    isArray : function (o) {
        return o && o.constructor.toString().indexOf('Array()') !== -1 || false;
    },
    
    /**
     * Valores comunes para las funciones de la pagina
     */
    defaults : {
        debug : 0,
        mensajes : {
            enviadoConExito: 'Muchas gracias por tu opinión. Sigue participando en cuatro.com',
            errorEnvio: 'Ha ocurrido un error al enviando tus datos. Inténtalo mas tarde',
            errorConectadoSuscripcion: 'Debes estar conectado para suscribirte'
        },
        ajaxConfig : {
            url : '/modulo/index.html',
            dataType : 'text/html'
            
        },
        alternateUrl: '/form/index.html',
        nicknameInfoUrl: '/usuario/nicknameinfo.html',
        add2FavHTML: ['<h2><span>Convierte Cuatro.com en tu página de inicio</span></h2>',
                      '<h2>Instrucciones</h2>',
                      '<p>Selecciona el menú superior <strong>Herramientas</strong>',
                      '» <strong>Opciones</strong></p>',
                      '<p>En el apartado <strong>Principal</strong> busca: ',
                      '<strong>Página de inicio</strong> e introduce <strong>http://www.cuatro.com</strong></p>'
                      ].join(''),
        loadMaskHTML : ['<div class=\"cto-loadmask preload\">',
                       '<div class=\"cto-loadmask-ctn\" ',
                       'style=\"text-align: center; position: relative; width: 100px;\">',
                       '<img src=\"/img/loading.gif\" ',
                       'class=\"cto-loadmask-img\" alt=\"\" style=\"margin: 0 auto;\">',
                       '<br /><p>Cargando...</p></div></div>'].join(''),
        loadMaskTimeout : 60000,
        jqmConfig : {
            modal : true,
            trigger : false,
            overlayClass : 'cto-win-overlay',
            closeClass : 'popup-btn-cerrar',
            overlay : 80,
            zIndex : 9000,
            onShow : function (win) {
                cto.getBodyIframe().show();
                win.w.show();
                $('.cto-flash').css('visibility', 'hidden');
                return true;
            },
            onHide : function (win) {
                cto.getBodyIframe().hide();
                win.w.hide();
                if (win.o) { win.o.remove(); }
                // @TODO: solo  mostrar si no hay otra ventana visible
                $('.cto-flash').css('visibility', 'visible');
                return true;
            }
        },
        trackPixel: {
            src: '/est.pl'
        },
        urlSoy: 'soy.cuatro.com',
        server: 'http://www.cuatro.com',
        urlTienda: 'de.cuatro.com',
        ajaxUPOS_prov: '/ajax/uposAX.php?op=provincias&pais=',
        ajaxUPOS_pob: '/ajax/uposAX.php?op=poblaciones&provincia='
    },
    validateDefaults : {
        errorElement: "span",
        errorPlacement: function (error, element) {
            error.appendTo(element.nextAll('.validacion:first'));
        },
        success: function (label) {
            label.html("Correcto!");
        },
        highlight: function (element, errorClass) {
            var el = $(element).nextAll('.validacion:first');
            el.removeClass('v-si').addClass('v-no');
        },
        unhighlight: function (element, errorClass) {
            var el = $(element).nextAll('.validacion:first');
            el.removeClass('v-no').addClass('v-si');
        }
    },

    
    /**
     * Retorna el popup de las bases legales
     */
    popupBasesLegales : function (ctn) {
      $('.' + ctn).click(function () {
        var url = $(this).attr('href'), popupBL;
        popupBL = window.open(url, 'bases_legales', 'height=600,width=400,scrollbars=yes,toolbar=no,directories=yes,status=no,menubar=no,resizable=yes');
        popupBL.focus();
        return false;
        });
    },
    
    /**
     * 
     */
    enviarEmail : function (id, type) {
        var user = cto.getCookieCuatro();
        if (!user) {
            cto.crm.alertLogin();
            return false;
        }
        cto.alert(
                ['<iframe  frameborder="no" scrolling="no" width="650" height="350" ',
                'id="iframeEnviarAmigo" src="/capas/capa_enviar_amigo.html',
                '?view=SendEmail&id=', id, 
                '&type=',  type, 
                '&user=', escape($.param(user)),  '"/>'].join('')
              );
        return false;
    },
    
    /**
     * 
     */
    enviarAmigo : function (id, type) {
        var user = cto.getCookieCuatro();
        
        if (!user) {
            cto.crm.alertLogin();
            return false;
        }
        cto.alert(
                  ['<iframe frameborder="no" scrolling="no" width="650" height="350" ',
                  'id="iframeEnviarAmigo" src="/capas/capa_enviar_amigo.html',
                  '?view=sendFriends&id=',  id, 
                  '&type=',  type, 
                  '&user=',  escape($.param(user)),  '" />'].join('')
                );
        return false;
    },
    enviarAmigoValid : function (str) {
        var expressionEmails = /^([^\(\);:,<>]+@[^\(\);:,<>]+\.[a-zA-Z]{2,4})$/;
        return expressionEmails.test(str);
    },
    enviarAmigoValidate : function (tipo, scope) {
        var valid, campoValid, clase, texto, expressionEmails = /^[0-9A-Za-z][0-9A-Za-z ]+$/;
        if (!scope) { scope = this; }
        if (tipo === 'email') { 
            valid = cto.enviarAmigoValid(scope.value); 
        } else if (tipo === 'nombre') {
            valid = expressionEmails.test(scope.value);
        }
        else { return false; }

        campoValid = $(scope).next();
        if (!campoValid || !campoValid.length) { $(scope).after("<p></p>"); }
        campoValid = $(scope).next();
        
        if (!valid) {
            clase = "validacion v-no";
            texto = "Valor no v&aacute;lido";
        } else {
            clase = "validacion v-si";
            texto = "Correcto";
        }
        campoValid.attr('class', clase);
        campoValid.html(texto);
    },
    mensajeLogReg : function (mensaje) {
        mensaje = mensaje.replace(/\[\[LOGIN\]\]/, '<a href = \"javascript:cto.parLogin();\">conectado</a>');
        mensaje = mensaje.replace(/\[\[REGISTRO\]\]/, '<a href = \"javascript:cto.parRegistro();\">registrado</a>');
        mensaje = mensaje.replace(/\[\[REGISTRO_AHORA\]\]/, '<a href = \"javascript:cto.parRegistro();\">hazlo ahora</a>');
        return mensaje;
    },
    parRegistro : function () {
        var pop = cto.getPopupWindow('cto-alert');
        pop.hide();
        cto.crm.alertRegistro();
    },
    parLogin : function () {
        var pop = cto.getPopupWindow('cto-alert');
        pop.hide();
        cto.crm.alertLogin();
    },
    
    overrideAlert : function () {
        var override;
        if (arguments.length) {
            override = arguments[0];
            if (override) {
                window.orig_alert = window.alert;
                window.alert = cto.alert;
                return true;
            } else {
                window.alert = window.orig_alert;
                delete window.orig_alert;
            }
        }
        
        return window.orig_alert ? true : false;
    },
    
    alert : function (msg, modal) {
        var id = 'cto-alert', win, replace;
        win = cto.getPopupWindow(id);
        if (!win) {
            win = cto.createPopupWindow({
                id : id,
                jqmConfig : {
                    modal : modal || false
                }
            });
            $(document).bind('keyup.alert', function (e) {
                if (e.which === $.keyCode.ESCAPE) {
                    win.jqmHide();
                }
            });
        }
        replace = win.is(':visible') ? false : true;
        cto.popupHTML(id, '<br />' + msg, replace);
        win.jqm($.extend(cto.defaults.jqmConfig, {
            modal : modal || false
        }));
        win.jqmShow();
        
    },
    
    getPopupWindow : function (id) {
        id = id ? id : 'cto-popup';
        return (cto.popups[id]) ? cto.popups[id] : false;
    },
    checkIframe : function () {
        if ($("#success_tpl")) {
            $("#fpopup_ugc").children("#success_tpl").parent("#fpopup_ugc").height(200);
        }
        return;
    },
    
    addOnLoadIframe : function () {
        return "onLoad = \"javascript: cto.checkIframe();\"";
    },
    
    createPopupWindow : function (config) {
        var win, id, jqmConfig, popupTab, popupButton, onl, addPopupWindow;
        
        addPopupWindow = function (id, win) {
            cto.popups[id] = win;
        };
        popupTab = function (config) {
            var id, idContent, content, tab;
            id = config.id ? config.id : cto.id();
            idContent = id + '-content';
            content = cto.wrap(config.html).html();
            tab = {
                label : $([
                    '<li id = "',  id, 
                    '"href = "#',  idContent, 
                    '" class = "',  (config.cls || ''), 
                    '"><a "href = "#',  idContent, 
                    '" >', config.label, '</a></li>'
                ].join('')),
                html : $('<div id = ' + idContent + '>' + content + '</div>')
            };
            if (config.load) {
                tab.label.find('a').bind('click.tab', function (e) {
                    $.get(config.load, null, function (data, status) {
                        tab.html.html(data);
                        tab.label.find('a').unbind('click.tab');
                    });
                    
                });
            }
            if (config.iframe) {
                tab.html = $(['<div id = ' + idContent + '>', '<iframe src = "' + config.iframe.src + '" ',
                              config.iframe.id ? ' id = "' + config.iframe.id || +'" ' : '',
                              ' width = "' + (config.iframe.width || '') + '" ',
                              ' height = "' + (config.iframe.height || '') + '" ',
                              (config.iframe.extra || ''), ' ></iframe><br /><br /></div>'].join(' '));
                if (config.iframe.onLoad) {
                    tab.html.find('iframe').load(function () {
                        config.iframe.onLoad.apply(this, [win]);
                    });
                }
            }
            return tab;
        };
        
        popupButton = function (config) {
            var id = config.id ? config.id : cto.id();
            return $(['<div id = "' + id + '" class = "btn rojo estirar ' + (config.cls || '') + '">',
                      '<span class = "i"></span><a href = "#">', config.label,
                      '</a><span class = "d"></span>', '</div>'].join(''));
        };
        
        id = config.id ? config.id : 'cto-popup';
        win = cto.getPopupWindow(id);
        if (!win) {
            win = $(['<div id = "' + id + '" class = "popup"  style = "display:none;">',
                     '<div id = "popup-up" class = "estirar">', '<p class = "logo">Cuatro</p>',
                     '<div class = "tabs idTabs"><ul></ul></div>',
                     '<div class = "btn-cerrar popup-btn-cerrar"><a href = "#">CERRAR</a></div>', '</div>',
                     '<div id = "popup-inner">', '<div class = "popup-inner-body">', '</div>',
                     '<div class = "popup-inner-buttons"></div>', '</div>', '<div id = "popup-down"></div>',
                     '</div>'].join(''));
            win.hide();
            $(document.body).append(win);
            jqmConfig = $.extend(cto.defaults.jqmConfig, config.jqmConfig);
            win.jqm(jqmConfig);
            if (config.buttons) {
                $(config.buttons.reverse()).each(function (i, e) {
                    var button = popupButton(e);
                    if (e.click) {
                        button.click(e.click);
                    }
                    win.find('.popup-inner-buttons').append(button);
                });
            }
            if (config.tabs) {
                $(config.tabs).each(function (i, e) {
                    var tab = popupTab(e);
                    tab.html.show();
                    win.find('.tabs').append(tab.label);
                    win.find('.popup-inner-body').append(tab.html);
                });
                win.find('.tabs').idTabs({
                    selected : '.marcado',
                    tag : 'li'
                }).find('a').click(function () {
                    this.blur();
                });
            } else if (config.iframe) {
                onl = cto.addOnLoadIframe();
                cto.popupHTML(id, ['<iframe ' + onl + ' src = "' + config.iframe.src + '" ',
                                   config.iframe.id ? ' id = "' + config.iframe.id + '" ' : '',
                                   ' width = "' + (config.iframe.width || '') + '" ',
                                   ' style = "' + (config.iframe.style || '') + '" ',
                                   ' height = "' + (config.iframe.height || '') + '" ',
                                   (config.iframe.extra || ''), ' ></iframe><br /><br />'].join(' '), true);
                if (config.iframe.onLoad) {
                    $('#' + id).find('iframe').load(function () {
                        config.iframe.onLoad.apply(this, [win]);
                    });
                }
                
            } else if (config.html) {
                cto.popupHTML(id, config.html);
            }
            // referencias rapidas a las funciones del plugin jqModal
            win.show = win.jqmShow;
            win.hide = win.jqmHide;
            
            addPopupWindow(id, win);
        }
        return win;
    },
    popupHTML : function (id, el, replace) {
        var body = $('#' + id).find('.popup-inner-body');
        if (replace) {
            body.html('');
        }
        if (!cto.isArray(el)) {
            el = [el];
        }
        $(el).each(function (i, e) {
            body.append(cto.wrap(e));
        });
    },
    
    popupTab : {
        next : function (id) {
            cto.popups[id].find('.idTabs li.marcado:first').next().trigger('click');
        },
        prev : function (id) {
            cto.popups[id].find('.idTabs li.marcado:first').prev().trigger('click');
        }
    },
    getLoadingMask : function (div, config) {
        var mask, ctn, id;
        config = $.extend({loadMaskHTML : cto.defaults.loadMaskHTML}, config);
        id = config.id ? '#cto-load-' + config.id.replace('.', '') : null;
        mask = $(id || '#cto-loadmask');
        div = $(div);
        if (!div.length) { return false; }
        
        if (!mask.length) {
            mask = $(config.loadMaskHTML);
            mask.hide();
            mask.attr('id', id);
            mask.css('position', config.position || 'absolute');
            mask.css('z-index', config.zIndex || '8999');
            mask.css('border', config.border || '#CCC 1px solid');
            mask.css('background', config.background || '#FFF');
            
            if (config.opacity) {
                mask.css('opacity', config.opacity);
            }
            
            // con esto lo agregamos al body
            mask.css('top', div.offset().top - 1);
            mask.css('left', div.offset().left - 1);
            mask.width(div.outerWidth({
                margin : true
            }) + 2);
            mask.height(div.outerHeight({
                margin : true
            }) + 2);
            
            ctn = mask.find('.cto-loadmask-ctn');
            ctn.css('top', (div.innerHeight() / 2) - (ctn.outerHeight() / 2));
            ctn.css('left', (div.innerWidth() / 2) - (ctn.outerWidth() / 2) - 50);
            // agrega la capa al body
            $(document.body).append(mask);
        }
        
        return {
            id : mask.attr('id'),
            mask : mask,
            show : function (nofade) {
                if (nofade) {
                    this.mask.show();
                } else {
                    this.mask.fadeToggle({
                        speed : 'fast'
                    });
                }
            },
            hide : function (nofade) {
                if (nofade) {
                    this.mask.hide();
                    this.mask.remove();
                } else {
                    this.mask.fadeToggle({
                        speed : 'fast',
                        callback : function () {
                            $(this).remove();
                        }
                    });
                }
            }
        };
    },
    getBodyIframe : function () {
        var ifr, $body;
        if (cto.bodyIframe === null) {
            $body = $(document.body);
            ifr = $(['<iframe id = "cto-ifr-overlay"frameborder = "0"' + ' width = "100%" height = "100%" ',
                    'vspace = "0" hspace = "0" scrolling = "no"', 
                    'marginheight = "0" marginwidth = "0"></iframe>'].join(''));
            ifr.css('position', 'absolute');
            ifr.attr('src', '');
            ifr.css('opacity', 0);
            ifr.css('z-index', 8999);
            ifr.css('top', 0);
            ifr.css('left', 0);
            ifr.css('width', $body.innerWidth() - 10);
            ifr.css('height', $body.innerHeight() - 1);
            ifr.hide();
            $body.append(ifr);
            cto.bodyIframe = {
                iframe : ifr,
                show : function () {
                    this.iframe.show();
                },
                hide : function () {
                    this.iframe.hide();
                }
                
            };
        }
        return cto.bodyIframe;
    },
    /** * TODO: A PARTIR DE AQUI PASAR TODO A PLUGINS ** */
    /** SUSCRIBIR RECURSO - START */
    suscribeme : function (presid) {
        cto.suscribir(presid, 'alta');
    },
    damedebaja : function (presid) {
        cto.suscribir(presid, 'baja');
    },
    suscribir : function (presid, paction) {
        var defaults, ops, user, suscribirSuccess, suscribirError, ajaxData, ajaxConfig;
        user = cto.getCookieCuatro();
        
        if (user === null) {
            cto.crm.alertLogin();
            return false;
        }
        
        suscribirSuccess = function (data, status) {
            if (data.success === true) {
                cto.alert(data.message);
            } else {
                cto.alert('Ha ocurrido un error procesar tu petición. Inténtalo mas tarde');
            }
        };
        
        suscribirError = function (data, status) {
            cto.alert('Ha ocurrido un error procesar tu petición. Inténtalo mas tarde');
        };
        
        defaults = {
            ajaxConfig : {
                dataType : 'json',
                type : 'POST'
            }
        };
        ops = $.extend({}, defaults, {});
        
        ajaxData = {
            modulo : 'SUS',
            resid : presid,
            format : 'JSON',
            action : paction
        };
        
        ajaxConfig = $.extend({}, cto.defaults.ajaxConfig, ops.ajaxConfig, {
            data : $.param(ajaxData),
            success : suscribirSuccess,
            error : suscribirError
        });
        
        $.ajax(ajaxConfig);
        
        return false;
    },
    
    /** SUSCRIBIR RECURSO - END */
    
    /** ENVIOSUGC - START */
    enviavideo : function (pconvid) {
        cto.enviaugc('video', pconvid);
    },
    enviaimagen : function (pconvid) {
        cto.enviaugc('imagen', pconvid);
    },
    enviatexto : function (pconvid) {
        cto.enviaugc('texto', pconvid);
    },
    
    enviaugc : function (ptipo, pconvid) {
        var defaults, ops, user, enviougcSuccess, enviougcError, ajaxData, ajaxConfig, popupwin, loginMsg;
        user = cto.getCookieCuatro();
        
        if (user === null) {
            loginMsg = 'Para participar, tienes que estar <a href="javascript:cto.parRegistro();">registrado</a>' +
                        ' y <a href="javascript:cto.parLogin();">conectado</a>; si aún no lo estás, ' +
                        '<a href="javascript:cto.parRegistro();">hazlo ahora</a>';
            cto.alert(loginMsg);
            return false;
        }
        
        popupwin = cto.getPopupWindow('popup_ugc');
        if (popupwin) {
            cto.ventanaUGC('popup_ugc', 'about:blank', 650, 410, 'scrolling = no frameborder = no');
        }
        
        enviougcSuccess = function (data, status) {
            var message, popupwin;
            if (data.success === true) {
                if (data.convst && data.userct && !data.userri && data.url) {
                    popupwin = cto.ventanaUGC('popup_ugc', data.url, 650, 410, 'scrolling = no frameborder = no');
                    popupwin = cto.getPopupWindow('popup_ugc');
                    popupwin.show();
                } else if (!data.convst) {
                    message = data.errmsg || 'No se pueden enviar materiales a esta convocatoria.';
                    cto.alert(message);
                } else if (!data.userst) {
                    if (data.userri) {
                        cto.crm.alertModificacion();
                    } else {         
                        message = data.errmsg || 'Debes estar conectado para participar';
                        cto.alert(message);
                    }        
                } else if (!data.userct) {
                    message = data.errmsg || 'Debes esperar para volver a participar.';
                    cto.alert(message);
                } else {
                    message = data.errmsg || 'Ha ocurrido un error procesar tu petición. Inténtalo mas tarde';
                    cto.alert(message);
                }
                
            } else {
                cto.alert('Ha ocurrido un error procesar tu petición. Inténtalo mas tarde');
            }
        };
        
        enviougcError = function (data, status) {
            cto.alert('Ha ocurrido un error procesar tu petición. Inténtalo mas tarde');
        };
        
        defaults = {
            ajaxConfig : {
                dataType : 'json',
                type : 'POST'
            }
        };
        ops = $.extend({}, defaults, {});
        
        ajaxData = {
            modulo : 'UGC',
            convtp : ptipo,
            convid : pconvid,
            usrid : user.id
        };
        
        ajaxConfig = $.extend({}, cto.defaults.ajaxConfig, ops.ajaxConfig, {
            data : $.param(ajaxData),
            success : enviougcSuccess,
            error : enviougcError
        });
        
        $.ajax(ajaxConfig);
        
        return false;
    },
    ventanaUGC : function (id, src, width, height, extra) {
        var win, config = {}, fid;
        win = cto.getPopupWindow(id);
        fid = 'f' + id;
        if (!win) {
            config = {
                id : id,
                html : $('contenido sin tabs'),
                iframe : {
                    id : fid,
                    src : src,
                    width : width,
                    height : height,
                    extra : extra
                },
                jqmConfig : {
                    modal : true
                }
            };
            win = cto.createPopupWindow(config);
        } else {
            win.find('#' + fid).attr('src', src);
        }
        return win;
    },
    /** ENVIOSUGC - END */

    random: function () {
        return (Math.floor(Math.random() * 100000) + '.' + (new Date()).getTime());
    },
    plural : function (num, txt) {
        var x, str;
        x = txt.split('|');
        str = x[0];
        if (!num) { num = 0; }
        if (num !== 1) {
            str = x[1] ? x[1] : x[0];
        }
        if (str.match(/%s/)) {
            str = str.replace(/%s/, num);
        }
        return str;

    },

    fillLogin : function () {
        var cUser, urlSoy, hrefUser, spanUser;
        cUser = cto.getCookieCuatro();
        $('#login_nologged .cto-link-registro').bind('click.login', function (e) {
            cto.crm.alertRegistro(); 
            e.preventDefault(); 
            return true; 
        });
        $('#login_nologged .cto-link-login').bind('click.login', function (e) {
            cto.crm.alertLogin(); 
            e.preventDefault(); 
            return true; 
        });
        if (cUser !== null) {
            $('div#login_logged').show();
            $('div#login_nologged').hide();
            $('div.cto-2balls').hide();
            // Now fill user data
            spanUser = $("span#usernick");
            spanUser.html(cUser.nick);
            // Enlace a soy
            urlSoy = $("#dominio_soy"); 
            if (urlSoy.length > 0) {
                urlSoy = urlSoy.attr("value");
            } else {
                urlSoy = false;
            }
            urlSoy = urlSoy ? urlSoy : cto.defaults.urlSoy;
            hrefUser = $("a#usernick_link");
            if (hrefUser.length === 0) {
                spanUser.wrap('<a id="usernick_link"></a>');
                hrefUser = $("a#usernick_link");
            }
            hrefUser.attr("href", "http://" + urlSoy + '/' + cUser.nick);
        } else {
            $('div#login_logged').hide();
            $('div#login_nologged').show();
            $('div.cto-2balls').show();
        }
    },

    /*** Para corregir el problema de los iframes ***/
    iframeFix : function () {
        var i, ifr;
        // solo aplicar para navegadores firefox
        if (!$.browser.mozilla) { return; }
        for (i = 0; i < window.frames.length; i += 1) {
            ifr = window.frames[i];
            try {
                if (ifr.document.location.href !== ifr.frameElement.src && 
                        !(ifr.document.location.href === document.location.href && ifr.frameElement.src === 'about:blank')) {
                    ifr.frameElement.src = ifr.frameElement.src;
                }
            } catch (e) {
                cto.log('error en iframe fix');
            }
        }
    },

    aleatorio: function (i, e) {
        var t;
        e = parseInt(e, 10);
        i = parseInt(i, 10);
        if (e > i) { t = i; i = e; e = t; }
        return (i + Math.round(Math.random() * (e - i)));
    },

    checkMyAvatar : function () {
        var tca = $.cookie('tca'), myavt;
        if (tca) {
            myavt = $('img:myavatar');
            if (myavt.length) {
                myavt.each(function (i, val) {
                    var $t = $(this), src = $t.attr('src');
                    if (! src.match(/tca=[0-9]*/gi)) {
                        $t.attr('src', $t.attr('src') + '?tca=' + tca);
                    }
                });
            }
        }
    },
    initVarios : function () {
        /* Carruseles */
        if ($.jcarousel) { $('.carrusel ul').jcarousel(); }
        
        $('.diseno-pagina-personal li')
            .mouseover(function () {
                $(this).addClass('over');
            })
            .mouseout(function () {
                $(this).removeClass('over');
            });
        
        /* Campos .select */
        $('.select')
            .find('li')
                .toggle(
                    function () {   $(this).addClass('on');     },
                    function () {   $(this).removeClass('on');  }
                   );
        
        $("#ow").hover(
            function () {
                $(this).addClass("visible");
            },
            function () {
                $(this).removeClass("visible");
            }
       );
        
        $(".otras").hover(
            function () {
                $("#ow").addClass("visible");
            },
            function () {
                $("#ow").removeClass("visible");
            }
       );
        
        $("#mw").hover(
            function () {
                $(this).addClass("visible");
            },
            function () {
                $(this).removeClass("visible");
            }
       );
        
        $(".mapa").hover(
            function () {
                $("#mw").addClass("visible");
            },
            function () {
                $("#mw").removeClass("visible");
            }
       );
        
    },

    esTienda : function () {
        var d = cto.parseURL(window.location.href);
        return d.host.match(cto.defaults.urlTienda) ? true : false;
    },
    reloadTop : function () {
        if (window.top.location.href !== window.location.href) {
            window.top.location.reload(); 
        } else {
            window.top.location.href = 'http://www.cuatro.com/';
        }
    },

    /** lanzador de todas las funciones necesarias onReady **/ 
    bootstrap : function () {
        cto.iframeFix(); 
        cto.fillLogin();
        cto.buscador.init();
        cto.checkMyAvatar();
        cto.initVarios();
        if (cto.staticPaging) { cto.staticPaging(); }
    }
    
};
cto.ns = cto.namespace; // alias

/** Extraido de jquery.ui.core */
jQuery.keyCode = {
    BACKSPACE : 8,
    CAPS_LOCK : 20,
    COMMA : 188,
    CONTROL : 17,
    DELETE : 46,
    DOWN : 40,
    END : 35,
    ENTER : 13,
    ESCAPE : 27,
    HOME : 36,
    INSERT : 45,
    LEFT : 37,
    NUMPAD_ADD : 107,
    NUMPAD_DECIMAL : 110,
    NUMPAD_DIVIDE : 111,
    NUMPAD_ENTER : 108,
    NUMPAD_MULTIPLY : 106,
    NUMPAD_SUBTRACT : 109,
    PAGE_DOWN : 34,
    PAGE_UP : 33,
    PERIOD : 190,
    RIGHT : 39,
    SHIFT : 16,
    SPACE : 32,
    TAB : 9,
    UP : 38
};

// plugin sencillo de fade in/out
jQuery.fn.fadeToggle = function (config) {
    config = config || {};
    return this.animate({
        opacity : 'toggle'
    }, config.speed, config.easing, config.callback);
};

/** plugin para agregar una url a marcadores. FF y IE. */
jQuery.fn.bookmarkThis = function (config) {
    var  defaults;
    config = config || {};
    defaults = { 
        title : window.document.title,
        url : window.location.href
    };
    config = jQuery.extend(defaults, config);
    this.unbind('click.bookmarkThis');
    this.bind('click.bookmarkThis', function (e) {
        try {
            if (jQuery.browser.msie && window.external) {
                e.preventDefault();
                window.external.AddFavorite(config.url, config.title);
            } else if (jQuery.browser.mozilla && window.sidebar && window.sidebar.addPanel) {
                e.preventDefault();
                window.sidebar.addPanel(config.title, config.url, "");
            } else {
                return true;
            } 
        } catch (err) {
            return true;
        }
    });
    return this;
};

/** plugin para cambiar la pagina de inicio en IE.  */
jQuery.fn.setHomePage = function (options) {
    var url;
    options = options || {};
    url = options.url || window.location.href;
    if (jQuery.browser.msie) {
        this.unbind('click.setHomePage');
        this.bind('click.setHomePage', function (e) {
            try {
                this.style.behavior = 'url(#default#homepage)';
                this.setHomePage(url);
                e.preventDefault();
            } catch (err) {
                return true;
            }
        });
    } else {
        if (options.fn) {
            this.bind('click.setHomePage', function (e) {
                options.fn.apply(this, options.args || []);
                e.preventDefault();
            });
        }
    }
    return this;
};

jQuery.cookie = function (name, value, options) {
    var expires = '', date, path, domain, secure, cookieValue = null, cookies, i, cookie;
    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options);
            options.expires = -1;
        }
        if (options.expires && (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + (options.path) : '';
        domain = options.domain ? '; domain=' + (options.domain) : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        if (document.cookie && document.cookie !== '') {
            cookies = document.cookie.split(';');
            for (i = 0; i < cookies.length; i += 1) {
                cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/*
 * plugin para limpiar texto por defecto al hacer blur. Al hacer foco se
 * selecciona todo
 */
jQuery.fn.clearOnFocus = function (defaultValue) {
    var $t = $(this);
    $t.data('defaultValue', defaultValue);
    return this.focus(function () {
        var v = $.trim($t.val());
        $t.val(v === $t.data('defaultValue') ? '' : v);
        $t.select();
    }).blur(function () {
        var v = $.trim($t.val());
        $t.val(v.match(/^\s+$|^$/) ? $t.data('defaultValue') : v);
    });
};



/*** CODIGO DEL BUSCADOR ***/

cto.buscador = {
    filtrosDefault : [ 'recientes', 'relevantes', 'valorados', 'visitados', 'comentados' ],
    str : 'Buscar...',
    filtros : { }, // se completan dinamicamente
    server: cto.defaults.server,
    esPaginaBuscador : function () {
        var url = cto.parseURL(window.location.href);
        return (url.segments.length && url.segments[0].match(/^(buscar|buscador|etiqueta)$/)) ? true : false;
    },
    tienda : 'de.cuatro.com',
    init : function () {

        var url = cto.parseURL(window.location.href), $this = cto.buscador;

        $this.baseURL = url.path;
        $this.base = '/buscar/';
        $this.quickSearch = false;
        // Buscamos si hay query en la url
        $this.parseQuery();

        // Primero los binds de los botones. 
        $this.binds();

        if (!$this.esPaginaBuscador()) { return; }

        // si estamos en pagina de buscador controlamos los filtros
        $this.bindsFiltros();
        $this.calcularFiltros();

    },
    prepareQuery : function () {
        var query, x;
        query = cto.buscador.query;
        for (x = 0; x < this.filtrosDefault.length; x += 1) {
            if (this.filtrosDefault[x] === query) {
                query = '';
            }
        }
        query = $.trim(query).toLowerCase();
        query = query.replace(/[\s]+/g, '-');
        query = (query === cto.buscador.str.toLowerCase()) ? 'todos': query; 
        return query;
    },
    parseQuery : function () {
        var $this = cto.buscador, url = cto.parseURL(window.location.href), query;
        query = '';

        if (url.segments[0].match(/buscar/) && url.segments.length > 1) {
            query = url.segments[1];
        } else if (url.segments[0].match(/buscador/) && url.segments.length > 2) {
            query = url.segments[2];
        } else if (url.segments[0].match(/etiqueta/) && url.segments.length > 1) {
            query = url.segments[1];
        }
        query = decodeURIComponent(query);
        query = (query === 'todos') ? '': query;

        $this.query = query.replace(/-/g, ' ');
    },
    binds : function () {
        var input = 'form#buscador input[name=query]', query;
        query = (cto.buscador.query) ? cto.buscador.query:cto.buscador.str;
        $(input).clearOnFocus(cto.buscador.str);
        $(input).val(query);

        $('form#buscador, form#buscador404').submit(function (ev) {
            if ($(input).val() === '' || $(input).val() === cto.buscador.str) { return false; }
            cto.buscador.quickSearch = true;
            cto.buscador.doSearch();
            ev.preventDefault();
        });
              
        $('form#buscador404 .cto-btn-buscar').click(function (ev) {
            cto.buscador.quickSearch = true;
            $(this).closest('form').trigger('submit');
            ev.preventDefault();
        });
    },
    recogerFiltros : function () {
        var form = $('form#buscar_filtro'), bus = cto.buscador, periodo_activo, orden_activo, programa_activo, f, filtros;

        // Valores seleccionados 
        filtros = { 
            cuatro: 'creador_cuatro',
            comunidad: 'creador_comunidad',
            videos: 'contenido_videos',
            fotos: 'contenido_fotos',
            blogs: 'contenido_blogs',
            participacion: 'contenido_particip',
            foros: 'contenido_grupos'
        };
        for (f in filtros) {
            if (filtros.hasOwnProperty(f)) { 
                bus.filtros[f] = form.find('input:checkbox[name="' + filtros[f] + '"]').is(':checked');
            }
        }

        periodo_activo = $('#buscadorRangoFechasListado li.activo a').attr('href').replace('#', '');
        bus.filtros[periodo_activo] = true;

        bus.filtros.tienda = $('#tienda').val() === '1' ? true : false;

        orden_activo = $('select#orden_buscador').val();
        bus.filtros[orden_activo] = true;

        bus.filtros.programa =  null;
        bus.filtros.id_programa =  null;

        programa_activo = form.find('select[name="busPrograma"]').val().toLowerCase();

        if (programa_activo !== 'todos') {
            bus.filtros.programa = programa_activo.split('/')[0];
            bus.filtros.id_programa = programa_activo.split('/')[1];
        }
    },
    bindsFiltros : function () {
        var bus = cto.buscador;

        // Tabs de periodo 
        $('#buscadorRangoFechasListado li:not(.activo) a').click(function (ev) {
            var $this = $(this), val = $this.attr('href').replace('#', '');
            $this.closest('ul').find('li.activo').removeClass('activo');
            $this.closest('li').addClass('activo');
            bus.clearFilter(['siempre', 'hoy', 'semana', 'mes']);
            bus.filtros[val] = true;
            bus.quickSearch = false;
            bus.doSearch();
            ev.preventDefault();
        });

        // Select de ordenacion
        $('select#orden_buscador').change(function (ev) {
            var $this = $(this), val = $this.val();
            bus.clearFilter(['relevantes', 'recientes', 'valorados', 'visitados', 'comentados']);
            bus.filtros[val] = true;
            bus.quickSearch = false;
            bus.doSearch();
            ev.preventDefault();
        });

        // boton filtrar resultados
        $("#buscadorSendFiltro").click(function (ev) {
            bus.pagina = 1;
            bus.quickSearch = false;
            bus.doSearch();
            ev.preventDefault();
        });
        
    },
    clearFilter : function (arr) {
        var i, bus = cto.buscador;
        for (i = 0;i < arr.length;i += 1) {
            bus.filtros[arr[i]] = false;
        }
    },
    calcularQuery : function () {
        var input, bus = cto.buscador, query;
        input = $('form#buscador input[name=query]').val();
        if (input !== bus.query && input !== bus.str) {
            bus.query = input;
        }
        query = bus.prepareQuery();
        if (query === 'todos' && bus.str_filtros === '') {
            query = '';
        } else if (query) {
            query = bus.prepareQuery() + '/';
        }
        bus.str_query = query;
    },
    calcularFiltros : function () {
        var bus = cto.buscador, filtros = [], url = cto.parseURL(window.location.href);
        bus.base = '/buscar/';

        if (bus.filtros.programa) {
            bus.base = '/buscador/' + bus.filtros.programa + '/';
            if (bus.str_query === '' && bus.filtros.programa) {
                bus.base = '/buscador/' + bus.filtros.programa + '/todos/';
            }
        } else {
            if (url.path.match(/^\/etiqueta\//)) {
                bus.base = '/etiqueta/';
                bus.etiqueta = true;
            } else if (typeof bus.str_query !== 'undefined') { 
                bus.base = '/buscar/';
            } 
            if (bus.str_query === '' || typeof bus.str_query === 'undefined') {
                bus.base = '/buscar/todos/';
            }
            if (bus.str_query === '*') {
                bus.base = '/buscar/todos/';
            }
        }
        // NOTA: se hacen sin while para mantener siempre el mismo orden
        if (bus.filtros.cuatro) {
            filtros[filtros.length] = 'cuatro';
        }
        if (bus.filtros.comunidad) {
            filtros[filtros.length] = 'comunidad';
        }

        if (bus.filtros.videos) {
            filtros[filtros.length] = 'videos';
        }

        if (bus.filtros.fotos) {
            filtros[filtros.length] = 'fotos';
        }

        if (bus.filtros.blogs) {
            filtros[filtros.length] = 'blogs';
        }

        if (bus.filtros.participacion) {
            filtros[filtros.length] = 'participacion';
        }

        if (bus.filtros.foros) {
            filtros[filtros.length] = 'foros';
        }

        if (bus.filtros.hoy) {
            filtros[filtros.length] = 'hoy';
        } else if (bus.filtros.semana)  {
            filtros[filtros.length] = 'semana';
        } else if (bus.filtros.mes)  {
            filtros[filtros.length] = 'mes';
        }

        if (bus.filtros.recientes) {
            filtros[filtros.length] = 'recientes';
        } else if (bus.filtros.valorados)  {
            filtros[filtros.length] = 'valorados';
        } else if (bus.filtros.visitados)  {
            filtros[filtros.length] = 'visitados';
        } else if (bus.filtros.comentados)  {
            filtros[filtros.length] = 'comentados';
        } 
        
        if ((cto.parseURL(window.document.referrer).host === bus.tienda) || (cto.parseURL(window.document.domain).host === bus.tienda) || bus.filtros.tienda) {
            filtros[filtros.length] = 'tienda';  
        }


        if (filtros.length) {
            bus.str_filtros =  filtros.join('-') + '/';
        }

    },
    doSearch : function (usarFiltro) {
        var  bus = cto.buscador, str_paginacion = '', query_string, url;
        if (!arguments.length) { usarFiltro = true; }
        bus.str_filtros = '';
        bus.str_query = '';

        if (usarFiltro && !bus.quickSearch) {
            bus.calcularQuery();
            bus.recogerFiltros();
        }
        bus.calcularFiltros();

        if (!bus.quickSearch) {
            if (bus.pagina && bus.pagina > 1) {
                str_paginacion = 'pagina-' + bus.pagina + '/';
            } else if (bus.pagina_tienda && bus.pagina_tienda > 1) {
                str_paginacion = 'pagina-tienda-' + bus.pagina_tienda + '/';
            }
        } else {
            bus.calcularQuery();
        }

        if (bus.str_query !== '' && bus.base === '/buscar/todos/') { bus.base = '/buscar/'; }

        query_string = $.param(cto.query(window.location.href));
        query_string = query_string ? '?' + query_string : '';

        url = bus.server + bus.base + (bus.str_query || '') + (bus.str_filtros || '') + str_paginacion + query_string;
        // SOLO DESARROLLO
        if (window.nosubmit) {
            cto.log(bus.base);
            cto.log(bus.str_query);
            cto.log(bus.str_filtros);
            cto.log(url);
            return false;
        }

        window.location = url;
    },
    paginar : function () {
        var bus = cto.buscador, query_string, str_paginacion = '', url;
        query_string = $.param(cto.query(window.location.href));
        query_string = query_string ? '?' + query_string : '';
        if (!bus.quickSearch) {
            bus.calcularQuery();
            bus.recogerFiltros();
        }
        bus.calcularFiltros();

        if (bus.pagina && bus.pagina > 1) {
            str_paginacion = 'pagina-' + bus.pagina + '/';
        } else if (bus.pagina_tienda && bus.pagina_tienda > 1) {
            str_paginacion = 'pagina-tienda-' + bus.pagina_tienda + '/';
        }
        url = bus.server + bus.base + (bus.str_query || '') + (bus.str_filtros || '') + str_paginacion + query_string;
        if (window.nosubmit) {
            cto.log(bus.base);
            cto.log(bus.str_query);
            cto.log(bus.str_filtros);
            cto.log(url);
            return false;
        }

        window.location = url;
    }
};

$.extend($.expr[':'], {
    avatar: function (a) {
        return $(a).attr('src').match(/\/avatar\//);
    },
    myavatar: function (a) {
        var c = cto.getCookieCuatro(), r;
        if (!c || !c.id) { return false; }
        r = new RegExp("\/" + c.id + "\/");

        return ($(a).attr('src').match(/\/avatar\//) && $(a).attr('src').match(r));
    }

});

/**** CRM ***/

cto.crm = {
    popupDefaults : {
        extra: 'scrolling=no frameborder=no',
        style: 'overflow-x: hidden;',
        width: 650
    },

    showPopup : function (ops) {
        var win, config = {}, fid, src;
        win = cto.getPopupWindow(ops.id);
        ops = $.extend({host: cto.defaults.server}, cto.crm.popupDefaults, ops);
        fid = 'f_' + ops.id;
        src = ops.host + ops.url;
        if (!win) {
            config = {
                id : ops.id,
                iframe : {
                    id: fid,
                    src: src,
                    width: ops.width,
                    height: ops.height, 
                    style: ops.style, 
                    extra: ops.extra
                },
                jqmConfig : {
                    modal : true
                }
            };
            win = cto.createPopupWindow(config);
        } else {
            win.find('#' + fid).attr('src', src);
        }
        win.show();
    },
    popups : {
        registro: { 
            id: 'popup_registro',
            url:  '/usuario/registro_capa.html',
            height: 400,
            extra: 'frameborder="no"'
        },
        registro_completo: {
            id: 'popup_registro',
            url:  '/usuario/registro_capa.html?completo=1',
            height: 400,
            extra: 'frameborder="no"'
        },
        registro_tienda: {
            id: 'popup_login_tienda',
            url: '/usuario/registro_capa.html?tienda=1&origen=' + document.location.href,
            height: 400,
            extra: 'frameborder=no'
        },
        recordar_clave: {
            id: 'popup_recordarclave',
            url:  '/usuario/recordarclave_capa.html',
            height: 170
        },
        modificacion_datos: {
            id: 'popup_modificacion',
            url:  '/usuario/modificacion_capa.html?sd=' + window.document.domain,
            height: 510
        },
        login: {
            id: 'popup_login',
            url: '/usuario/login_capa.html?origen=' + document.location.href,
            height: 300
        },
        login_tienda: {
            id: 'popup_login_tienda',
            url: '/usuario/login_capa.html?tienda=1&origen=' + document.location.href,
            height: 300
        },
        legal: {
            id: 'popup_legal',
            url:  '/usuario/legal_capa.html',
            height: 440
        },
        privacidad: {
            id: 'popup_privacidad',
            url:  '/usuario/privacidad_capa.html',
            height: 440
        },
        perfil_privado: {
            id: 'popup_perfilprivado',
            url:  '/usuario/cambiar_perfil_privado.html?origen=' + window.document.domain,
            height: 80
        },
        perfil_publico: {
            id: 'popup_perfilpublico',
            url:  '/usuario/cambiar_perfil_publico.html?origen=' + window.document.domain,
            height: 80
        },
        marcar_amigo: {
            id: 'popup_amistad',
            url: '/amistad_capa.html?origen=' + window.document.domain,
            height: 100
        },
        cambiar_avatar: {
            id: 'popup_cambiaravatar',
            url:  '/usuario/cambiar_avatar.html?origen=' + window.document.domain,
            height: 350
        }
    },
    alertRegistro : function (tienda) { 
        var conf = tienda ? cto.crm.popups.registro_tienda : cto.crm.popups.registro;
        cto.crm.showPopup(conf); 
    },
    alertRegistroCompleto : function () {
        cto.crm.alertRegistro(true);
    },
    alertRegistroTienda : function () {
        cto.crm.alertRegistro(true);
    },
    alertRecordarClave : function () { 
        cto.crm.showPopup(cto.crm.popups.recordar_clave); 
    },
    alertModificacion : function () {
        cto.crm.showPopup(cto.crm.popups.modificacion_datos);
    },
    alertLogin : function (tienda) { 
        var conf = tienda ? cto.crm.popups.login_tienda : cto.crm.popups.login;
        cto.crm.showPopup(conf); 
    },
    alertLoginTienda : function () { 
        cto.crm.alertLogin(true);
    },
    alertLegal : function () { 
        cto.crm.showPopup(cto.crm.popups.legal); 
    },
    alertPrivacidad : function () { 
        cto.crm.showPopup(cto.crm.popups.privacidad);
    },
    alertAmigo : function () { 
        cto.crm.showPopup(cto.crm.popups.marcar_amigo); 
    },
    alertCambiarAvatar : function () { 
        cto.crm.showPopup(cto.crm.popups.cambiar_avatar); 
    },
    alertCambiarPerfil : function (perfil) { 
        var estado = $('form input[name="perfilEsPublico"]').val();
        if (estado === perfil) { return; }
        cto.crm.showPopup((perfil === 'publico') ? cto.crm.popups.perfil_publico :  cto.crm.popups.perfil_privado);
    }, 
    init : function () {
        $('.cto-cambiar-avatar').click(function () {
            cto.crm.alertCambiarAvatar();
        });
    },
    initPortada : function () {
        cto.crm.init();   
        $('.perfil-botonera .cto-perfil-save').click(function (e) {
            $('form#perfil-portada').submit();
            e.preventDefault();
        });
        $('.cto-cambiar-perfil.cto-estado-privado, .cto-cambiar-perfil.cto-estado-publico').click(function (e) {
            cto.crm.alertCambiarPerfil($(this).hasClass('cto-estado-publico') ? 'publico' : 'privado');
            e.preventDefault();
        });
    },
    initAlertas : function () {
        cto.crm.init();   
        var form;
        $('.cto-perfil-privacidad').click(function (e) {
            cto.crm.alertPrivacidad();
            e.preventDefault();
        });
        $('.cto-perfil-legal').click(function (e) {
            cto.crm.alertLegal();
            e.preventDefault();
        });
        form = $('form.datos-personales');
        $('.cto-alertas-save', form).click(function (e) {
            var aceptaBases = $('input[name=acepto]:checked', form).length ? true:false;

            $('#resultado .validacion.v-si', form).text('');
            if (!aceptaBases) {
                $('#resultado .validacion', form).show();
            } else {
                $('#resultado .validacion', form).hide();
                form.submit();
            }           
            e.preventDefault();
                
        });
    },
    initLogin : function () {
        var form = $('form#form_login'), validator;
        validator = form.validate($.extend({}, cto.validateDefaults, {
            rules: {
                ema: {
                    required: true,
                    email: true
                },
                cla: {
                    required: true,
                    minlength: 2
                }
            },
            messages: {
                ema: {
                    required: 'Valor no valido',
                    email: 'Email invalido'
                },
                cla: {
                    required: 'Valor no valido',
                    minlength: 'Valor no valido'
                }
            },
            errorContainer: "form#form_login #msg",
            submitHandler: function (f) {
                if (validator.numberOfInvalids() === 0) {
                    form.find('#errmsg').hide();
                }
                f.submit();
            }

        }));
        form.valid();

        $('.cto-login-send').click(function () { form.submit(); });

    },
    initRegistro : function (tienda) {
        var form = $('form#form_registro'), validator;

        validator = form.validate($.extend({}, cto.validateDefaults, cto.crm.registro_rules, {
            errorContainer: "form#form_registro #msg",
            submitHandler: function (f) {
                if (validator.numberOfInvalids() === 0) {
                    form.find('#errmsg').hide();
                }
                f.submit();
            }

        }));

        cto.crm.controlFecha({
            form : form,
            dia : $('select[name="nac1"]', form),
            mes : $('select[name="nac2"]', form),
            anio : $('select[name="nac3"]', form)
        });
        if (tienda) {
            cto.crm.controlUPOS({form : form});
        }

        form.valid();

        $('.cto-registro-send').click(function (e) { form.submit(); e.preventDefault(); });
        $('.cto-info-nickname').click(function (e) {
            window.top.cto.alert($('#cto-texto-nickname').html(), true);
        });
        $('.cto-info-nickname-ventana').click(function (e) {
        	var popupNickInfo = window.open(cto.defaults.nicknameInfoUrl, 'nickname_info', 'height=400,width=400,scrollbars=no,toolbar=no,directories=no,status=no,menubar=no,resizable=no');
            popupBL.focus();
            e.preventDefault();
        });

    },
    initPerfil : function () {
        var form = $('form#form_perfil'), validator;

        validator = form.validate($.extend({}, cto.validateDefaults, cto.crm.perfil_rules, {
            errorContainer: "form#form_perfil #msg",
            submitHandler: function (f) {
                if (validator.numberOfInvalids() === 0) {
                    form.find('#errmsg').hide();
                }
                f.submit();
            }

        }));

        form.valid();

        $('.cto-perfil-send').click(function (e) { form.submit(); e.preventDefault(); });
        $('.cto-perfil-cambiar-clave').click(function (e) {
            $('input#cambia_clave_check', form).val(1); 
            $('#passwd-paso1').hide(); 
            $('#passwd-paso2').fadeIn(); 
            form.valid();
            e.preventDefault();
        });
        $('.usu-mas-info').click(function (e) {
            window.top.cto.alert($('#cto-texto-nickname').html(), true);
        });

    },
    controlFecha : function (conf) {
        var form, dia, mes, anio, fnac, calcFechaNac, clickFn;
        form = conf.form;
        dia = conf.dia || $('select[name="usr_fecnac_dia"]', form);
        mes = conf.mes || $('select[name="usr_fecnac_mes"]', form);
        anio = conf.anio || $('select[name="usr_fecnac_anio"]', form);
        fnac = conf.fnac || $('input[name="hd_nac"]', form);

        calcFechaNac = function () {
            var d = parseInt(dia.val(), 10),
                m = parseInt(mes.val(), 10),
                a = parseInt(anio.val(), 10);
            d = d >= 10 ? d : '0' + d;
            m = m >= 10 ? m : '0' + m;
            fnac.val(d + '-' + m + '-' + a);
            form.validate().element(fnac);
        };

        calcFechaNac();
        clickFn = function (e) { calcFechaNac(); };
        dia.change(clickFn);
        mes.change(clickFn);
        anio.change(clickFn);


    },
    controlUPOS : function (conf) {
        var form = conf.form,
            $pais = $('#pais', form), 
            $prov = $('#prov', form), 
            $pob = $('#pob', form),
            $hd_pais = $('input[name="pais_required"]', form),
            $hd_prov = $('input[name="prov_required"]', form),
            $hd_pob  = $('input[name="pob_required"]', form);

        function getUPOSData(el, index, url, fnCallback) {
            var text = el.text();
            el.attr('disabled', 'disabled').find('option:selected').attr('text', 'Cargando...');
            $.getJSON(url, function (data) {
                el.attr('disabled', '').find('option:selected').attr('text', text);
                $.each(data[index], function (code, name) {
                    el.append( $('<option>'+ name +'</option>').attr('value', code) ); // en IE solo funciona asi
                });
                if (typeof fnCallback === 'function') {
                    fnCallback.apply(el, [data[index]]);
                }
            });
        }

        function checkRequired() {
            $hd_pais.val($pais.find('option').length > 1 ? 1 : 0);
            $hd_prov.val($prov.find('option').length > 1 ? 1 : 0);
            $hd_pob.val($pob.find('option').length > 1 ? 1 : 0);
            form.valid();
        }

        function emptySelect(el, msg) {
            $(el).empty().append($('<option>'+msg+'</option>').attr({'selected':true}));
        }

        $pais.change(function (e) {
            var code_pais = $pais.val(),
                url = cto.defaults.ajaxUPOS_prov + code_pais;

            emptySelect($prov, 'Seleccione una provincia');
            emptySelect($pob, 'Seleccione una poblacion');
            if (!code_pais) {
                return;
            }

            getUPOSData($prov, 'provincias', url, checkRequired);

        });
        if (!$prov.val()) {
            $pais.change();
        } 

        $prov.change(function (e) {
            var code_prov = $prov.val(),
                url = cto.defaults.ajaxUPOS_pob + code_prov;

            emptySelect($pob, 'Seleccione una poblacion');
            getUPOSData($pob, 'poblaciones', url, checkRequired);

        });
        if (!$prov.val()) {
            $prov.change();
        }

        $pob.change(function (e) {
            checkRequired();
        });

    },
    initDatosPersonales : function () {
        var validator, 
            form = $('form#mod_perfil');

        validator = form.validate($.extend({}, cto.validateDefaults, cto.crm.datospersonales_rules, {
            errorContainer: "form#mod_perfil #msg",
            submitHandler: function (f) {
                if (validator.numberOfInvalids() === 0) {
                    form.find('#errmsg').hide();
                }
                f.submit();
            }
        }));
        $('.cto-datos-send').click(function (e) { form.submit(); e.preventDefault(); });

        cto.crm.controlFecha({form : form});
        cto.crm.controlUPOS({form : form});

        form.valid();
    }

};

/**** CRM - END***/


/** @TODO: Revisar esta funcion **/
cto.cambiaFondo = function (cual) {
    var numTemas, i;
    $("#fondo_" + cual).addClass('marcado');
    $("#activado_" + cual).html('<p>SELECCIONADO</p>');
    numTemas = $('.diseno-pagina-personal.caja-perfil').find('li[id^=fondo]').length;
    for (i = 0;i <= numTemas; i++) {
        if (i !== cual && $("#fondo_" + i).hasClass("marcado")) {
            $("#fondo_" + i).removeClass("marcado");
            $("#activado_" + i).html('<p class="lnk naranja"><a href="javascript:cto.cambiaFondo(' + i + ')">Seleccionar</a></p>');
        }
    }
    $('form[name=descripcion] input[name=fondo_seleccion]').val(cual);
};

/** FUNCIONES DE INICIO **/
$(cto.bootstrap);

