jQuery(function () {
    $("img").lazyload({ failurelimit : 20 });
    /*
    $(window).bind("load", function() {
        $("img").trigger("sporty");
    });
    */
})

/* jQuery timer */
jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});
jQuery.extend({
    timer: {
        guid: 1,
        global: {},
        regex: /^([0-9]+)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseInt(result[1], 10);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }

            times = times || 0;
            belay = belay || false;

            if (!element.$timers)
                element.$timers = {};

            if (!element.$timers[label])
                element.$timers[label] = {};

            fn.$timerID = fn.$timerID || this.guid++;

            var handler = function() {
                if (belay && this.inProgress)
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };

            handler.$timerID = fn.$timerID;

            if (!element.$timers[label][fn.$timerID])
                element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);

            if ( !this.global[label] )
                this.global[label] = [];
            this.global[label].push( element );

        },
        remove: function(element, label, fn) {
            var timers = element.$timers, ret;

            if ( timers ) {

                if (!label) {
                    for ( label in timers )
                        this.remove(element, label, fn);
                } else if ( timers[label] ) {
                    if ( fn ) {
                        if ( fn.$timerID ) {
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    } else {
                        for ( var fn in timers[label] ) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for ( ret in timers[label] ) break;
                    if ( !ret ) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for ( ret in timers ) break;
                if ( !ret )
                    element.$timers = null;
            }
        }
    }
});
if (jQuery.browser.msie) {
    jQuery(window).one("unload", function() {
        var global = jQuery.timer.global;
        for ( var label in global ) {
            var els = global[label], i = els.length;
            while ( --i )
                jQuery.timer.remove(els[i], label);
        }
    });
}
/* Fin jQuery timer */

/*!
 * jQuery iFrame Inheritance
 *
 * Copyright (c) 2009 Eric Garside (http://eric.garside.name)
 * Dual licensed under:
 *      MIT: http://www.opensource.org/licenses/mit-license.php
 *      GPLv3: http://www.opensource.org/licenses/gpl-3.0.html
 */
(function($){

	// Create a function in the Global Namespace so we can access
	// it from the iFrame by calling parent.inherit()
	this.inherit = function(child){
		// First, bind a copy of jQuery down into the DOM of the
		// iFrame, so we can hook in functionality. Things may get
		// a bit confusing here, as we're creating this function in
		// the parent, but have to set it up internally to get called
		// as if it were in the child.
		child.jQueryInherit = this.parent.jQuery;

		// Bind a special ready callback binding function, to handle the
		// scope of responding to the document.ready hook instead of the
		// parent's document.ready
		child.jQueryInherit.fn.ready = function( fn ) {
			// Attach the listeners
			child.jQueryInherit.hooks.bindReady();

			// If the DOM is already ready
			if (child.jQueryInherit.hooks.isReady)
				// Simply trigger the callback
				fn.call( child.document, child.jQueryInherit );

			// Otherwise, remember it so we can trigger it later
			else
				child.jQueryInherit.hooks.readyList.push( fn );

			return this;
		}

		// Create a namespace for hooking some functionality to the
		// iFrame, like document.ready decetion and handling
		child.jQueryInherit.hooks = {
			isReady: false,
			readyBound: false,
			readyList: [],
			// Mimic the readyBind() function in the child, so it can
			// set up the listeners for document.ready
			bindReady: function(){
				if (child.jQueryInherit.hooks.readyBound) return;
				child.jQueryInherit.hooks.readyBound = true;

				// 	Mozilla, Opera, and webkit nightlies support
				if ( child.document.addEventListener ) {
					child.document.addEventListener( "DOMContentLoaded", function(){
						child.document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
						child.jQueryInherit.hooks.ready();
					}, false );

				// For IE
				} else if ( child.document.attachEvent ) {
					// ensure firing before onload,
					// maybe late but safe also for iframes
					child.document.attachEvent("onreadystatechange", function(){
						if ( child.document.readyState === "complete" ) {
							child.document.detachEvent( "onreadystatechange", arguments.callee );
							child.jQueryInherit.hooks.ready();
						}
					});

					// If IE and not an iframe
					// continually check to see if the document is ready
					if ( child.document.documentElement.doScroll && child == child.top ) (function(){
						if ( child.jQueryInherit.hooks.isReady ) return;

						try {
							// If IE is used, use the trick by Diego Perini
							// http://javascript.nwbox.com/IEContentLoaded/
							child.document.documentElement.doScroll("left");
						} catch( error ) {
							setTimeout( arguments.callee, 0 );
							return;
						}

						// and execute any waiting functions
						child.jQueryInherit.hooks.ready();
					})();
				}

				// A fallback to window.onload, that will always work
				jQuery.event.add( child, "load", child.jQueryInherit.hooks.ready );
			},
			// Hook the ready trigger to fire off the hook bindings
			ready: function(){
				// Make sure the DOM is not already loaded
				if ( !child.jQueryInherit.hooks.isReady ) {
					// Remember that the DOM is ready
					child.jQueryInherit.hooks.isReady = true;

					// If there are functions bound...
					if ( child.jQueryInherit.hooks.readyList ) {
						// Execute them all
						jQuery.each( child.jQueryInherit.hooks.readyList, function(){
							this.call( child.document, child.jQueryInherit );
						});

						// Reset the list of functions
						child.jQueryInherit.hooks.readyList = null;
					}

					// Trigger any bound ready events
					jQuery(child.document).triggerHandler('ready');
				}
			}
		};

		return child.jQuery = child.$ = function( selector, context ){
			// Test and see if we're handling a shortcut bind
			// for the document.ready function. This occurs when
			// the selector is a function. Because firefox throws
			// xpconnect objects around in iFrames, the standard
			// jQuery.isFunction test returns false negatives.
			if (selector.constructor.toString().match(/Function/) != null)
				return child.jQueryInherit.fn.ready( selector );

			// Otherwise, just let the jQuery init function handle the rest. Be sure we pass in
			// proper context of the child document, or we'll never select anything useful.
			else
				return child.jQueryInherit.fn.init(selector||this.document, context||this.document);
		}
	}

})(jQuery);
/* jQuery inheritance */

app = {};
app.SKINURL = '/wp-content/themes/tonterias/';
app.loginWindow = {url: "/wp-login2.php?iframe=true", title: "&nbsp;",w: 700, h: 190};
$jq = jQuery;
$jq(function () {
    /* Qtip Modal */
    $jq(".add_favorite_link, .remove_favorite_link, .ajax-link").live("click", linkAjax );

    $jq(".login_add_favorite_link_login").click(function () {
        qtipLogin(function() {
            _a = $("body").data("a_link_fav");
            $(_a).each(linkAjax);
        });
        $("body").data("a_link_fav",this);
        return false;
    });

        try {
        jQuery("a.load-form-login").fancybox({
            hideOnContentClick: false
        });
        } catch(e) {}

        jQuery("#commentform").submit(function () {

            if(jQuery("#commentform textarea[name=comment]").val().length == 0) {
                alert("Debes escribir un comentario");
            } else {
                if(!jQuery(this).hasClass("logged")) {
                    qtipLogin(function () {
                        jQuery("#commentform input[type=submit]").trigger("click");
                    });
                } else {
                   jQuery("#commentform input[type=submit]").trigger("click");
                   return true;
                }
            }

            return false;
        });
});
function qtipLogin(callback) {
    qtipModal(app.loginWindow.url, app.loginWindow.title, app.loginWindow.w, app.loginWindow.h, callback);
}
function qtipModal(url,title,w,h,callback) {
    $('#qtip-blanket').remove();
    $('<div id="qtip-blanket">')
      .css({
         position: 'absolute',
         top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
         left: 0,
         height: $(document).height(), // Span the full document height...
         width: '100%', // ...and full width

         opacity: 0.7, // Make it slightly transparent
         backgroundColor: 'black',
         zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
      })
      .appendTo(document.body) // Append to the document body
      .hide(); // Hide it initially

     $a = jQuery("<a href='#'></a>").qtip({
            content: {
         title: {
            text: title,
            button: 'Cerrar'
         },
         text: "<iframe width="+w+" height="+h+" src='"+url+"' frameborder=0></iframe>"
      },
      position: {
         target: $(document.body), // Position it via the document body...
         corner: 'center' // ...at the center of the viewport
      },
      show: {
         when: 'click', // Show it on click
         solo: true // And hide all other tooltips
      },
      hide: false,
      style: {
         width: w,
         padding: 0,
         border: {
            width: 9,
            radius: 9,
            color: '#666666'
         },
         name: 'light'
      },
      api: {
         beforeShow: function()
         {
            // Fade in the modal "blanket" using the defined show speed
            $('#qtip-blanket').fadeIn(this.options.show.effect.length);
         },
         beforeHide: function()
         {
            // Fade out the modal "blanket" using the defined hide speed
            $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
         }
      }});
        $("body").append($a);
        $a.click();
        if(callback != undefined) {
            $(".qtip").data("relEvent", callback);
        }
}
    function cerrarModalQtip () {
        relEvent = $(".qtip").data("relEvent")
        $(".qtip, #qtip-blanket").remove();
        relEvent.call();
    }
     function linkAjax() {
            $div = $jq(this).parent();
            $div.addClass("favorite-loading").html("Procesando...");
            $jq.get($jq(this).attr("href")+"&rnd="+Math.floor ( Math.random ( ) * 100000 + 1 ), {} , function (data) {
                    $div.removeClass("favorite-loading").html(data);
            });
            return false;
    }
function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

function contribuirSubmit(_frm) {
    var _tipo = null;
    if(jQuery(_frm).hasClass("form-imagen-form").length > 0) {
        _tipo = "imagen";
    } else if(jQuery(_frm).hasClass("form-video-form").length > 0) {
        _tipo = "video";
    } else if(jQuery(_frm).hasClass(".form-enlace-form").length > 0) {
        _tipo = "enlace";
    };

    jQuery(".error-form").remove();
    
    error = false;
    jQuery(_frm).find(".required").each(function () {
       _fld = jQuery(this);
       if(_fld.val().length == 0) {
           error = true;
           _fld.parent().append("<div class='error-form'>"+_fld.attr("rel")+"</div>");
           _fld.change(function () {
              jQuery(this).parent().find(".error-form").remove();
              jQuery(this).removeClass("input-error")
//              jQuery(this).unbind("change");
           });
           _fld.addClass("input-error");
       }
    });

    if(_tipo == "imagen") {
        if(jQuery(_frm).find("input[name=archivo[]]").length == 0) {
            error = true;
            jQuery(_frm).find(".archivos").append("<div class='error-form error-archivos'>Debes enviar un archivo</div>");
        }
    } else if(_tipo == "video") {
        if(jQuery(_frm).find("textarea[name=embed_code]").val().length == 0 && jQuery(_frm).find("input[name=archivo[]]").length == 0) {
            error = true;
            jQuery(_frm).find(".archivos").append("<div class='error-form error-archivos'>Debes añadir un codigo embebido o enviar un archivo</div>");
        }
    } else if(_tipo == "enlace") {
        var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
        $_link = jQuery(_frm).find("input[name=link]");
	if($_link.val().length > 0 && !regexp.test($_link.val())) {
            error = true;
            $_link.parent().append("<div class='error-form error-archivos'>No es un enlace válido</div>");
            $_link.addClass("input-error");
        }
    }

    if(jQuery(_frm).find("input[type=checkbox][name=condiciones]:checked").length == 0) {
        error = true;
        _chk = jQuery(_frm).find("input[type=checkbox][name=condiciones]");
        _chk.parent().append("<div class='error-form'>Debes aceptar las condiciones para continuar</div>");
        _chk.click(function () {
            jQuery(this).parent().find(".error-form").remove(); 
        });
    }
    if(!error) {
        _pars = $jq(_frm).serialize();
        try {

        $jq.get("?"+_pars, {}, function (data) {
            $jq(".contribuir_link").html( data );
        });
        } catch(ex) {
            alert(ex.message);
        }
    }
    return false;
}

function contribuir_form(path) {
        _upf = {
            'uploader'       : path + '/swf/uploadify.swf',
            'script'         : path + '/uploadify.php',
            'cancelImg'      : path + '/images/cancel.png',
            'buttonImg'      : path + '/images/agregar-archivo.gif',
            'folder'         : '/wp-content/uploads/users/',
            'queueID'        : 'fileQueue',
            'auto'           : true,
            'multi'          : true,
            'buttonText'     : 'Añadir archivo',
            'width'          : 90,
            'height'          : 20
        };

        jQuery(".quitar-archivo").live("click", function () {
            $d = jQuery(this).parent();
            $d.remove();
        });
        complete = function(fileObj, _tipo) {
            /* event: The event object.
            queueID: The unique identifier of the file that was completed.
            fileObj: An object containing details about the file that was selected.

             * name – The name of the file
             * filePath – The path on the server to the uploaded file
             * size – The size in bytes of the file
             * creationDate – The date the file was created
             * modificationDate – The last date the file was modified
             * type – The file extension beginning with a ‘.'

            response: The data sent back from the server.
            data: Details about the file queue.

             * fileCount – The total number of files left in the queue
             * speed – The average speed of the file upload in KB/s
             */
            _file = fileObj.filePath.split("/");
            _file = _file[_file.length - 1];

            _d = '<div><input type="hidden" name="archivo[]" value="'+fileObj.filePath+'">' +
            '<img src="'+path+'/images/pixel.gif" class="icon-check" width="16" height="16"/> ' +
            '<img src="'+path+'/images/pixel.gif" class="icon-remove quitar-archivo" width="16" height="16"/>'+
            '&nbsp; '+_file+
            '</div>';

            $jq(".form-"+_tipo+" #contribuir-form .archivos").prepend(_d);

            $jq(".form-"+_tipo+" .error-archivos").remove();
        }
        uplodifyError = function (event, queueID, fileObj, type, info) {
            /*
             * event: The event object.
                queueID: The unique identifier of the file that returned an error.
                fileObj: An object containing details about the file that was selected.
                    name – The name of the file
                    size – The size in bytes of the file
                    creationDate – The date the file was created
                    modificationDate – The last date the file was modified
                    type – The file extension beginning with a ‘.'
                    errorObj: An object containing details about the error returned.
                type – Either ‘HTTP', ‘IO', or ‘Security'
                info – An error message describing the type of error returned
             */
            if(info == undefined) {
                alert("No es posible subir archivos en un sitio protegido con clave");
            }
        }
        uploadifyCompleteImg = function (ev, queueID, fileObj, response, data) {
            complete(fileObj, "imagen");
        }
        uploadifyCompleteVideo = function (ev, queueID, fileObj, response, data) {
            complete(fileObj, "video");
        }
        uploadifyCompletePowerpoint = function (ev, queueID, fileObj, response, data) {
            complete(fileObj, "powerpoint");
        }

        jQuery("#uploadify").uploadify(
            jQuery.extend(_upf, {
            fileDesc: 'Imagenes',
            fileExt: '*.jpg;*.gif;*.png;*.jpeg',
            onComplete      : function (ev, queueID, fileObj, response, data) {

                jQuery("#uploadifyUploader").remove();
                jQuery("#uploadify2").uploadify(
                jQuery.extend(_upf, {
                    fileDesc: 'Imagenes',
                    fileExt: '*.jpg;*.gif;*.png;*.jpeg',
                    'buttonImg'      : path + '/images/agregar-otro-archivo.gif',
                    'width'         : 120,
                    onComplete      : uploadifyCompleteImg,
                    onError       : uplodifyError
                }));
                uploadifyCompleteImg(ev, queueID, fileObj, response, data);
            },
            onError       : uplodifyError
        }));
        
        jQuery("#uploadify3").uploadify(
        jQuery.extend(_upf, {
            fileDesc: 'Videos',
            fileExt: '*.avi;*.mov;*.mpg;*.mp4;*.3gp;*.flv',
            onComplete      : uploadifyCompleteVideo,
            onError       : uplodifyError
       }));

        jQuery("#uploadify4").uploadify(
        jQuery.extend(_upf, {
            fileDesc: 'Powerpoint',
            fileExt: '*.ppt;*.pps',
            onComplete      : uploadifyCompletePowerpoint,
            onError       : uplodifyError
       }));

        jQuery(".form-colaboraciones input[type=radio]").click(function () {
           _id = jQuery(this).val();
           jQuery(".form-colaboraciones .form").hide();
           jQuery(".form-colaboraciones .form-"+_id).show();
           jQuery(".form-colaboraciones .form-"+_id+" .cond").append(jQuery(".form-colaboraciones .condiciones").show());
        });
}


// Connect

function update_userbox(name, image, url, logout) {
    //populate the data in #userbox and show it
    jQuery('#userbox').html( "<a href='"+url+"'>"
    + "<img alt='"+name+"' src='"+image+"' />"
    + "Logged in as " + name + "</a> "
    + "(<a href='./index.php' onclick='" + logout + "'>logout</a>)" ).show();
    //hide name input and service
    //login buttons
    jQuery('#userinfo').hide();
    //populate the values of the inputs
    //using data from service
    jQuery('#name').val(name);
    jQuery('#url').val(url);
    jQuery('#image').val(image);
}
    initProfile = function () {
        jQuery(".update_profile #pais").change(function () {
            var $_cmb = jQuery(this);
            jQuery.get("", {"_profile_provinces": true, "pais": jQuery(this).val()}, function(data) {
                try {
                    _prov = eval(" ("+data+") ");
                } catch(e) {
                    _prov = {};
                }
                var _cmb_prov = jQuery(".update_profile #provincia");
                _cmb_prov.html("");
                
                if(_prov == null) {
                    if(jQuery("tr.edit:visible").length>0) {
                        jQuery("tr.tr-provincia-edit").hide();
                    }
                } else {
                    if(jQuery("tr.edit:visible").length>0) {
                        jQuery("tr.tr-provincia-edit").show();
                    }
                    jQuery(_prov).each(function() {
                        _cmb_prov.append("<option value='"+this.value+"'>"+this.nombre+"</option>");
                    });
                }
//                */
                if($_cmb.data("onLoad") == true) {
                    idProv = $_cmb.data("idProv");
                    jQuery("#provincia option[value="+idProv+"]").attr("selected","selected");
                    $_cmb.data("onLoad",false)
                }
            });
        });
        jQuery(".update_profile .reset").click();
        jQuery(".update_profile").submit(function () {
            var $_form = jQuery(this);
            var _error = false;

            $i_first_name = $_form.find("input[name=first_name]");
            if($i_first_name.val().length == 0) {
                app.profile.showTipsy($i_first_name.get(0));
                _error = true;
            }
            $i_sexo = $_form.find("select[name=sexo]");
            if($i_sexo.find("option:selected").val() == "") {
                app.profile.showTipsy($i_sexo.get(0));
                _error = true;
            }
            $i_pais = $_form.find("select[name=pais]");
            if($i_pais.find("option:selected").val() == "" || $i_pais.find("option:selected").val() == "NULL" ) {
                app.profile.showTipsy($i_pais.get(0));
                _error = true;
            }
            $i_provincia = $_form.find("select[name=provincia]:visible");
            if($i_provincia.length > 0 && $i_provincia.find("option:selected").val() == "" ) {
                app.profile.showTipsy($i_provincia.get(0));
                _error = true;
            }
            
            if(!_error) {
                jQuery.post("?_update_profile=true&rnd="+rand(10000), jQuery(this).serializeArray(), function (data) {
                    mostrarDato("todos", false);
                    app.profile.datosForm(data, $_form);
                    jQuery(".show_edit").removeAttr("disabled");
                });
            }

            return false;
        });


        jQuery(".update_profile .show_edit").click(function () {
            $_form = jQuery(this).parents(".update_profile");
            mostrarDatoForm($_form, true);
            return false;
        });
        jQuery(".update_profile .cancel_edit").click(function () {
            jQuery(".show_edit").removeAttr("disabled");
            var $_form = jQuery(this).parents("form");
            jQuery.get("?_datos_perfil=true", {}, function (data) {
                app.profile.datosForm(data, $_form);
            });
            mostrarDatoForm($_form, false);
            return false;
        });

        jQuery(".cancelar").click(function () {
            $tr = jQuery(this).parents(".edit");
            mostrarDato($tr, false);
        });
        /*
         Quitado 23/12
        try {
            jQuery(".accordion").accordion({autoHeight: false});
        } catch(e) { }
        */
       
        var lastsel;
        gridimgpath = '/';
        gridEditRow = function () {
            id = jQuery(this).attr("rel");
            if(id == undefined) {
                id = this.selrow;
            }
            if(id && id!==lastsel){
                jQuery("#row_amigos").setRowData(lastsel,{act:""});
                jQuery('#row_amigos').restoreRow(lastsel);

                se = "<button type='button' value='S' class='gridSaveRow' rel='"+id+"'><img src='"+app.SKINURL+"images/disk-small.png'></button>";
                ce = "<button type='button' value='C' class='gridRestoreRow' rel='"+id+"'><img src='"+app.SKINURL+"images/cross-small-circle.png'></button>";
                
                jQuery("#row_amigos").setRowData(id,{act:se+ce});

                jQuery('#row_amigos').editRow(id,true);
                lastsel=id;
            }
        };
        jQuery(".gridEditRow").live("click", function () {
            gridEditRow();
            return false;
        });
        jQuery(".gridDeleteRow").live("click", function() {
            id = jQuery(this).attr("rel");
            jQuery("#row_amigos").delGridRow(id);
            return false;
        });
        jQuery(".gridRestoreRow").live("click", function() {
            id = jQuery(this).attr("rel");
            jQuery("#row_amigos").restoreRow(id);
            gridRowInitial(id);
            return false;
        });
        gridOnSaveRow = function(data) {
            try {
                _d = eval(" (" + data.responseText + ") ");
                jQuery("#row_amigos").setRowData(_d.ID,{act:""});
                jQuery('#row_amigos').restoreRow(_d.ID);
                gridRowInitial(_d.ID);
            } catch(e) {
                _d = {};
            }
            return true;
        };
        gridLoadComplete = function() {
            var ids = jQuery("#row_amigos").getDataIDs();
            for(var i=0;i<ids.length;i++) {
                gridRowInitial(ids[i]);
            }
        };
        gridRowInitial = function(id) {
            be = "<button type='button' value='E' class='gridEditRow' rel='"+id+"'><img src='"+app.SKINURL+"images/pencil-small.png'></button>";
            bd = "<button type='button' value='D' class='gridDeleteRow' rel='"+id+"'><img src='"+app.SKINURL+"images/eraser-small.png'></button>";
            jQuery("#row_amigos").setRowData(id,{act:be+bd});
        };
        jQuery(".gridSaveRow").live("click",function () {
            jQuery("#row_amigos").saveRow(jQuery(this).attr("rel"),gridOnSaveRow);
        });
        try {
            jQuery("#row_amigos").jqGrid({
                url:'?_lista_amigos&q=',
                datatype: "json",
                colNames:['Acciones','Nombre', 'Email'],
                colModel:[
                    {name:'act',index:'act', width:75,sortable:false},
                    {name:'name',index:'name', width:200, editable:true},
                    {name:'email',index:'email', width:200,editable:true}
                ],
                rowNum:20,
                rowList:[10,20,30],
                imgpath: gridimgpath,
                pager: jQuery('#prow_amigos'),
                sortname: 'id',
                viewrecords: true,
                sortorder: "asc",
                loadComplete: gridLoadComplete,
                onSelectRow: gridEditRow,
                editurl: "?_lista_amigos=true&_accion=save",
                caption: "Tus amigos",
                height: '400px'
            }).navGrid("#prow_amigos",{
                edit:false,add:false,del:false
            });
        } catch(e) {
        }
    };
    app.profile = {};

    app.profile.showTipsy = function(o) {
        tipsyShowHover(o, {gravity: 'w'});
        hideTipsy = function () {
            tipsyHideHover(this);
            jQuery(this).unbind();
        };
        jQuery(o).focus(hideTipsy);
    };

    app.profile.datosForm = function(data, $form) {
        if($form.hasClass("update_profile")) {
            _tipo = "datos";
        } else if($form.hasClass("update_intereses")) {
            _tipo = "intereses";
        } else if($form.hasClass("update_email")) {
            _tipo = "email";
        }
        
        try {
            _d = eval(" ("+data+") ");
        } catch(e) {
            _d = {};
        }

        if(_tipo == "datos") {
            jQuery(".eup_first_name").html(_d.eup_first_name);
            jQuery(".eup_web").html(_d.eup_web);
            jQuery(".eup_sexo").html(_d["eup_nombre_sexo"]);
            jQuery(".eup_fecha-nac").html(_d["eup_fecha_nac_label"]);
            jQuery(".eup_pais").html(_d["eup_nombre_pais"]);
            jQuery(".eup_provincia").html(_d["eup_nombre_prov"]);

            if(jQuery(".eup_provincia").html() == "") {
                jQuery(".tr-provincia-dato").hide();
            }
            // Volver atras form
            jQuery("#first_name").val(_d.eup_first_name);

            jQuery("#sexo option[value='"+_d.eup_sexo+"']").attr("selected","selected");
            if(_d["mostrar_sexo"] == 1) {
                jQuery("#mostrar-sexo").attr("selected","selected");
            } else {
                jQuery("#mostrar-sexo").removeAttr("selected");
            }
            _fecha_nac = _d["eup_fecha_nac"].split("-");
            jQuery("#fecha-d option[value='"+_fecha_nac[2]+"']").attr("selected","selected");
            jQuery("#fecha-m option[value='"+_fecha_nac[1]+"']").attr("selected","selected");
            jQuery("#fecha-y option[value='"+_fecha_nac[0]+"']").attr("selected","selected");

            jQuery("#mostrar-fecha option[value="+_d["eup_mostrar_fecha"]+"]").attr("selected","selected");

            jQuery("#pais option[value='"+_d["eup_pais"]+"']").attr("selected","selected");
            jQuery("#pais").data("onLoad",true).data("idProv",_d["eup_provincia"]).change();

            if(_d["eup_web"].length == 0) {
                jQuery("#web").html("http://");
            } else {
                jQuery("#web").html(_d["eup_web"]);
            }
            
        } else if(_tipo == "intereses") {
            jQuery(".eup_musica-favorita").html(_d["eup_musica_favorita"]);
            jQuery(".eup_citas-favoritas").html(_d["eup_citas_favoritas"]);
            jQuery(".eup_acerca-de-mi").html(_d["eup_acerca_de_mi"]);

            jQuery("#musica-favorita").val(_d["eup_musica_favorita"]);
            jQuery("#citas-favoritas").val(_d["eup_citas_favoritas"]);
            jQuery("#acerca-de-mi").val(_d["eup_acerca_de_mi"]);
        } else if(_tipo == "email") {
            jQuery(".eup_email").html(_d["eup_email"]);
            jQuery("#email").val(_d["eup_email"]);
        }
    };
    app.profile.updateEmail = function () {
        jQuery("#update_email .show_edit").click(function () {
           $form = jQuery(this).parents("form");
           mostrarDatoForm($form, true);
           return false;
        });
        jQuery("#update_email").submit(function () {
            var $form = jQuery(this);

            var $i_email = $form.find("input[name=email]");
            $i_email.attr("title","Debes ingresar un email");
            error = false;
            if($i_email.val().length == 0) {
                app.profile.showTipsy($i_email.get(0));
                error = true;
            }
            if(!error) {
                jQuery.post("?_update_email=true&email="+$i_email.val()+"&rnd="+rand(10000), jQuery(this).serializeArray(), function (data) {
                    try {
                        _d = eval("( "+data+" )");
                    } catch(e) {
                        _d = {};
                    }

                    if(_d.status == "OK") {
                        mostrarDatoForm($form, false);
                        app.profile.datosForm(data, $form);
                        jQuery(".show_edit").removeAttr("disabled");
                    } else {
                        $i_email.attr("title",_d.message);
                        jQuery.data($i_email.get(0), 'active.tipsy', null);
                        app.profile.showTipsy($i_email.get(0));
                    }
                });
            }
            return false;
        });
        jQuery("#update_email .cancel_edit").click(function () {
            var $_form = jQuery(this).parents("form");
            jQuery.get("?_datos_perfil=true&email=true", {}, function (data) {
                app.profile.datosForm(data, $_form);
            });
            mostrarDatoForm($_form, false);
            $(form).find("input").each(function () {
                tipsyHideHover(this);
                jQuery(this).unbind();
            })

            return false;
        });
    };
    app.profile.updateIntereses = function () {
        jQuery(".update_intereses .show_edit").click(function () {
           $form = jQuery(this).parents("form");
           mostrarDatoForm($form, true);
           return false;
        });
        jQuery(".update_intereses").submit(function () {
            var $form = jQuery(this);
            jQuery.post("?_update_profile=true&rnd="+rand(10000), jQuery(this).serializeArray(), function (data) {
                mostrarDatoForm($form, false);
                app.profile.datosForm(data, $form);
                jQuery(".show_edit").removeAttr("disabled");
            });
            return false;
        });
        jQuery(".update_intereses .cancel_edit").click(function () {
            var $_form = jQuery(this).parents("form");
            jQuery.get("?_datos_perfil=true", {}, function (data) {
                app.profile.datosForm(data, $_form);
            });
            mostrarDatoForm($_form, false);
            return false;
        });
    };
    app.profile.cambiarClave = function () {
        jQuery("#cambiar_clave").submit(function () {
            $form = jQuery(this);
            _data = $form.serializeArray();
            jQuery.post("?_cambiar_clave=true&rnd="+rand(10000), _data, function (data) {
                try {
                    _d = eval("( "+data+" )");
                } catch(e) {
                    _d = {};
                }
                if(_d.status == "OK") {
                    jQuery(".tipsy").remove();
                    $form.find("input[name=clave_actual]").val("");
                    $form.find("input[name=nueva_clave]").val("");
                    $form.find("input[name=repita_clave]").val("");
                    alert("Clave modificada correctamente");
                } else {
                    $i = $form.find("input[name="+_d.field+"]");
                    $i.attr("title",_d.message);
                    jQuery.data($i.get(0), 'active.tipsy', null);
                    app.profile.showTipsy($i.get(0));
                }
            });
            return false;
        });
    };
    app.profile.quitarFavoritos = function() {
        jQuery(".mfp_remove_link").click(function () {
            var $li = jQuery(this).parents("li");
            _fav_id = jQuery(this).attr("rel");

            jQuery.get("?", {_remove_fav: true, fav_id: _fav_id}, function (data) {
                try {
                    _d = eval("( "+data+" )");
                } catch(e) {
                    _d = {};
                }
                if(_d.status == "OK") {
                    $li.hide("slow").remove()
                } else {
                    alert(_d.message);
                }
            });
            return false;
        });
    };
    app.profile.traerAmigos = function () {
        jQuery("#traer_amigos_form").submit(function () {
            var $form = jQuery(this);
            error = false;
            $i_user = $form.find("input[name=user]");
            if($i_user.val().length == 0) {
                app.profile.showTipsy($i_user.get(0));
                error = true;
            }
            $i_pass = $form.find("input[name=password]");
            if($i_pass.val().length == 0) {
                app.profile.showTipsy($i_pass.get(0));
                error = true;
            }
            if(!error) {
                jQuery(this).append("<input type=hidden name='_ajax' value='true' >");
                jQuery.post("?_invitar_amigos=true", jQuery(this).serializeArray() , function (data) {
                    try {
                        _d = eval("( "+data+" )");
                    } catch(e) {
                        _d = {};
                    }
                    if(_d.status == "OK") {
                        alert("Se agregaron "+_d.cant_amigos+" nuevo(s) amigo(s)")
                        $form.find("input[name=user]").val("");
                        $form.find("input[name=password]").val("");
                        jQuery("#row_amigos").trigger("reloadGrid");
                    } else {
                        alert(_d.message);
                    }
                });
            }
            return false;
        });
    }
    jQuery(function () {
        try {
            initProfile();
            app.profile.updateEmail();
            app.profile.updateIntereses();
            app.profile.cambiarClave();
            app.profile.quitarFavoritos();
            app.profile.traerAmigos();
        } catch(e) {
            alert(e.message);
        }
    })

function mostrarDato($tr, editar) {
    if($tr == "todos") {
        if(editar) {
            jQuery("tr.dato").hide();
            jQuery("tr.edit").show();
        } else {
            jQuery("tr.dato").show();
            jQuery("tr.edit").hide();
        }
    } else {
        mostrarCampos = function(editar, _rel) {
            if(editar) {
                jQuery("tr[rel="+_rel+"].dato").hide();
                jQuery("tr[rel="+_rel+"].edit").show();
            } else {
                jQuery("tr[rel="+_rel+"].dato").show();
                jQuery("tr[rel="+_rel+"].edit").hide();
            }
        }
        _rel = $tr.attr("rel");
        if(_rel == undefined) {
            $tr.parent().find(".edit").each(function () {
                _rel = jQuery(this).attr("rel");
                mostrarCampos(editar,_rel);
            });
        } else {
            mostrarCampos(editar,_rel);
        }
    }
}
function mostrarDatoForm($form, editar) {
    if(editar) {
        $form.find("tr.dato").hide();
        $form.find("tr.edit").show();
        if(jQuery(".tr-provincia #provincia option").length == 0) {
            jQuery(".tr-provincia-edit").hide();
        }
    } else {
        $form.find("tr.dato").show();
        $form.find("tr.edit").hide();
        if(jQuery(".tr-provincia-dato .eup_provincia").html().length == 0) {
            jQuery(".tr-provincia-dato").hide();
        }
    }
}

/* Avatar */
jQuery(function () {
   if(jQuery("#avatar-profile").length>0) {
       jQuery("#avatar-profile a").click(function () {
           return false;
       });
       jQuery("#avatar-profile img, .cambiar-avatar").click(function () {
           
           qtipModal("/cambiar-avatar.php", "Cambiar Avatar", 600, 460, function() {});
           /*
           jQuery("#divModal").html('<iframe id="modalIframeId" width="100%" height="100%" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" />')

           .dialog({modal: true, width: 600, height: 460, resizable: false, dragabble: false, title: "Cambiar avatar"})
           .dialog("open");
           
           jQuery("#modalIframeId").attr("src","/cambiar-avatar.php");
           */
            return false;
       });
   }
});

/* Ultimas acciones */
jQuery(function () {
    enviarTonteria = function() {
        qtipModal($(this).attr("href"),"Enviar tontería", 520,400);
            return false;
    };
    $(".enviar-tonteria").click(enviarTonteria);
    $(".enviar-tonteria-login").click(function () {
        qtipLogin(function() {
            _a = $("body").data("a_link_enviar");
            $(_a).each(enviarTonteria);
        });
        $("body").data("a_link_enviar",this);
        return false;
    });

    $(".comment-reply-link").click(function () {
       $("#respond h3").html("Responde a este comentario");
       $("#commentform #submit").parent().prepend($("#commentform #cancel-comment-reply-link"));
    });
    $(".comment-login").click(function () {
        
    });
    $("#cancel-comment-reply-link").click(function () {
       $("#respond h3").html("Añade tu comentario");
    });

    $(".descargar-archivo-login").click(function () {
        qtipLogin(function () {
            _a = $("body").data("a_descargar_archivo");
            $(_a).attr("href",$(_a).attr("alt"));
            $(_a).unbind("click");
            $(_a).click();
        });
        $("body").data("a_descargar_archivo", this);
        return false;
    });

    setQtipTonteriasRelacionadas = function (nuevos) {
        $(".related-posts a").attr("title","");
        $( ( nuevos ? ".related-posts li.nuevos a img[alt]" : ".related-posts a img[alt]" ) ).qtip({
            content: {
                text: false
            },
            position: 'bottomMiddle',
            hide: {
                fixed: true
            },
           style: {
                padding: 5,
                marginLeft: 5,
                fontWeight: 'bold',
                border: {width: 3},
                width: 140,
                textAlign: 'center',
                name: 'dark'
            }
        });
    };
    setQtipTonteriasRelacionadas(false);

    $(".mas-tonterias-similares").live("click", function () {
        var $a = $(this);
        $a.data("html",$a.html());
        $a.html("Cargando ...").attr("disabled","disabled");
        post_ID = $a.attr("rel");
        var desde = $a.data("desde");
        if(desde == null) {
            desde = 8;
        }
        $.get("?mas-tonterias-similares=true&post_ID="+post_ID+"&desde="+desde, {}, function(data) {
            $(".related-posts ul").append(data);
            desde += 12;
            $a.data("desde",desde);
            setQtipTonteriasRelacionadas(true);
            $a.html($a.data("html"));
        });
        $(".related-posts").oneTime('5s',function () {
           $(this).find(".nuevos").removeClass("nuevos");
        });
        return false;
    });
});

$(function () {
    $(".sugerencias-link").click(function () {
        qtipModal("/sugerencias.php","Sugerencias",400,310);
        return false;
    });
    $('#message_box').centerScreen();
    $(window).scroll(function () {
        $('#message_box').centerScreen();
    });

    tipoMenu = function(o) {
        tipo = false;
        if($(o).hasClass("videos-tab")) {
            tipo = "videos";
        } else if($(o).hasClass("imagenes-tab")) {
            tipo = "imagenes";
        } else if($(o).hasClass("juegos-tab")) {
            tipo = "juegos";
        } else if($(o).hasClass("powerpoint-tab")) {
            tipo = "powerpoint";
        } else if($(o).hasClass("enlaces-tab")) {
            tipo = "enlaces";
        } else if($(o).hasClass("audios-tab")) {
            tipo = "audios";
        } else if($(o).hasClass("animaciones-tab")) {
            tipo = "animaciones";
        } else if($(o).hasClass("textos-tab")) {
            tipo = "textos";
        } else if($(o).hasClass("fondos-tab")) {
            tipo = "fondos";
        } else if($(o).hasClass("colabora-tab")) {
            tipo = "colabora";
        } else if($(o).hasClass("ayuda-tab")) {
            tipo = "ayuda";
        }
        return tipo;
    }
    var _hover_menu;
    categoriaActual = function () {
        $("#tabbar .categoria-activa").each(function () {
            tipo = tipoMenu(this);
            if(tipo != false) {
                $("#tabbar a").removeClass("a-hover");
                $(this).find("a").addClass("a-hover");
                $("#top-tags table").hide();
                $("#top-tags table."+tipo).show();

                $("#navigation").attr("class","nav nav-"+tipo);
            }
        });
    };
    $("#tabbar li").hover(function () {
        _hover_menu = true;
        tipo = tipoMenu(this);
        if(tipo != false) {
            $("#tabbar a").removeClass("a-hover");
            $(this).find("a").addClass("a-hover");
            $("#top-tags table").hide();
            $("#top-tags table."+tipo).show();

            $("#navigation").attr("class","nav nav-"+tipo);
        }
    }, function () {
        _hover_menu = false;
    });
    $("#navigation").hover(function () {
        _hover_menu = true;
    }, function () {
        _hover_menu = false;
    });
    setInterval(function() {
        if(!_hover_menu) {
            categoriaActual();
        }
    }, 300)

});

jQuery.fn.centerScreen = function(loaded) {
    var obj = this;
    if(!loaded) {
    obj.css('top', $(window).height()/2-this.height()/2);
//    obj.css('left', $(window).width()/2-this.width()/2);
    $(window).resize(function() {obj.centerScreen(!loaded);});
    } else {
        obj.stop();
        obj.animate({top: $(window).height()/2-this.height()/2
        /* , left: $(window).width()/2-this.width()/2 */ }, 200, 'linear');
    }
}

function closeDialog(img_avatar) {
    if(img_avatar != undefined) {
        $(".avatar").attr("src",img_avatar);
    }
    cerrarModalQtip();
    //$("#divModal").dialog("close");
}
$(function () {
    if(_fullscreen==undefined) {
        _fullscreen = false;
    }
   Shadowbox.init({
       onClose: function (o,b) {
           $.get("/ajax.php",{}, function (data) {
                try {
                    d = eval(" ("+data+") ");
                    if(d.logged) {
                        if($(o.el).hasClass("comment-reply-login")) {
                            _f = $(o.el).attr("rel2");
                            eval(" "+_f+" ");
                            $("#form-commentario").show();
                            $("#form-commentario textarea").focus();
                            $(".link-loguearse").hide();
                        } else if($(o.el).hasClass("login_add_favorite_link")) {
                            $(o.el).attr("href",$(o.el).attr("rel2"));
                            $(o.el).each(linkAjax);
                        } else if($(o.el).hasClass("descargar-archivo")) {
                            $(".descargar-archivo").replaceWith("<a class='descargar-archivo' href='"+$(".descargar-archivo").attr("alt")+"'>Descargar</a>")
                            $(".descargar-archivo").unbind().click();
                            document.location.href= $(".descargar-archivo").attr("href");
                        } else {
                            $("#form-commentario").show();
                            $("#form-commentario textarea").focus();
                            $(".link-loguearse").hide();
                        }
                    } else {
//                        alert("not logged");
                    }
                } catch(e) {
                }
           });
       },
       width: 300,
       height: 300
   });
   function shadowbox_close() {
        Shadowbox.close();
   }
    // Juego a tamaño maximo
    _w = $(".page-content .flashmovie object").width();
    _h = $(".page-content .flashmovie object").height();
    _r = _h / _w;
    if(_fullscreen) {
        _w = 950;
        _h = 950 * _r;
        $(".page-content .flashmovie object").attr("width", _w).attr("height", _h);
    }
});
function _browser(str) {
        (navigator.userAgent.toLowerCase().indexOf(str)+1) ? ret = true : ret = false;
        return ret;
}
function _getFlashObj(movie){
   if (window.document[movie]) {
      return window.document[movie];
   }
   if (navigator.appName.indexOf("Microsoft Internet")==-1) {
      if (document.embeds && document.embeds[movie]) {
         return document.embeds[movie];
      }
   } else {
      return document.getElementById(movie);
   }
}
function _SWFZoom(d) {
        _id = $("object").attr("id");
        obj = _getFlashObj(_id);

        nw = obj.width;
        nh = obj.height;

        if (d==0) {
                nw = obj.width*0.9;
                nh = obj.height*0.9;
        } else {
                nw = obj.width*1.1;
                nh = obj.height*1.1;
        }
        obj.setAttribute("width",nw);
        obj.setAttribute("height",nh);

        if(_fullscreen) {
            _ancho_columna = 950;
        } else {
            _ancho_columna = 400;
        }
        if(nw > _ancho_columna) {
            $(".col-izq").css("width",nw + 20 + "px");
            $(".post-box").css("width",nw + 5 + "px");
            if($(".col-izq").width() > 950) {
                $(".overflow").css("width",nw + 35 + "px");
                $(".page-body").css("width",nw + 35 + "px");
            }
        } else {
            $(".col-izq").css("width", "");
            $(".post-box").css("width", "");
            $(".overflow").css("width","");
        }
        return false;
}

$(".audioplayer_container").prepend("<span style='color:black; font-size: 12px; font-weight:bold; position:relative; top:-10px; visibility:visible; margin-right: 10px;'>Pulsa play --></span>");

function _zoom(_z) {
    
        _id = $("object").attr("id");
        obj = _getFlashObj(_id);
        
        if($(obj).data("w") == null) {
            nw = obj.width;
            nh = obj.height;
            $(obj).data("w",nw).data("h",nh);
        } else {
            nw = $(obj).data("w");
            nh = $(obj).data("h");
        }

        nw = nw * (_z / 100);
        nh = nh * (_z / 100);
        
        obj.setAttribute("width",nw);
        obj.setAttribute("height",nh);

        if(_fullscreen) {
            _ancho_columna = 950;
        } else {
            _ancho_columna = 400;
        }
        if(nw > _ancho_columna) {
            $(".col-izq").css("width",nw + 20 + "px");
            $(".post-box").css("width",nw + 5 + "px");
            if($(".col-izq").width() > 950) {
                $(".overflow").css("width",nw + 35 + "px");
                $(".page-body").css("width",nw + 35 + "px");
            }
        } else {
            $(".col-izq").css("width", "");
            $(".post-box").css("width", "");
            $(".overflow").css("width","");
        }
        return false;
}

// Zoom juegos
$(function () {
    if($(".zoom-flash .slider").length > 0) {
        $slider = $(".zoom-flash .slider").slider({
            value: 100,
            min: 10,
            max: 200,
            step: 1,
            change: function(ev, ui) {
                _zoom(ui.value);
            },
            slide: function(ev, ui) {
                _zoom(ui.value);
            },
        });
        sliderVal = function(_v) {
            $slider.slider("value", $slider.slider("value") + _v);
        };
        $(".zoom-flash .mas").click(function () {
            sliderVal(10);
        })
        $(".zoom-flash .menos").click(function () {
            sliderVal(-10);
        });
    }
})