/*
==================================================
@author Soluciones Corporativas IP, SLU (SCIP)
==================================================
*/

/*============================================================
  Funciones generales
============================================================*/

function redirect(url) {
	document.location.href = url;
}

function STO(func,time) {
	return window.setTimeout(func,time);
}

function aleatorio(inf,sup) {
	return parseInt(inf) + Math.round(Math.random() * (sup-inf));
}

function GetAnchor( o ) {
	if(typeof(o)!='string') {
		o = $(o).attr('href');
	}
	return o.replace(/^.*\#/,'');
}

function Domain2jquery(domain) {
	return domain.replace(/\./g,'\\.');
}

function strip_tags(str) {
	return str.replace(/<([^>])+>/g,'');
}

function isBrowserIE(version,equal) {
	if($.browser) {
		if($.browser.msie) {
			if(equal) {
				return version>0 ? $.browser.version == version : true;
			}
			return version>0 ? $.browser.version < version : true;
		}
		return false;
	}
	return true;
}
function isBrowserMozilla() {
	if($.browser) {
		return $.browser.mozilla;
	}
	return true;
}

function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
}

//http://plugins.jquery.com/project/Cookie
//last version: 	2008-Jan-26
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var dd_plugin_search = {
	url: 'http://www.dondominio.com/search-plugin.xml',
	src: '',
	title: 'Plugin de búsqueda de dominios en DonDominio.com',
	section: 'Dominios'
}

function installSearchEngine() {
	if (window.external && ("AddSearchProvider" in window.external)) { // Firefox 2 and IE 7, OpenSearch
		window.external.AddSearchProvider(dd_plugin_search.url);
	} else if (window.sidebar && ("addSearchEngine" in window.sidebar)) { // Firefox <= 1.5, Sherlock
		window.sidebar.addSearchEngine(dd_plugin_search.url,dd_plugin_search.src,dd_plugin_search.title,dd_plugin_search.section);
	} else { // No search engine support (IE 6, Opera, etc).
		alert("No search engine support");
	}
}

function CaptureMousePosition(e) {
	var pos_x = 0, pos_y = 0;
	if(!e) var e = window.event;
	if(e.pageX || e.pageY) { pos_x = e.pageX; pos_y = e.pageY; }
	else if(e.clientX || e.clientY) { pos_x = e.clientX + document.body.scrollLeft; pos_y = e.clientY + document.body.scrollTop };
	return [pos_x, pos_y];
}

/*============================================================
  Funciones de chequeo de datos
============================================================*/

function check_ccc(ccc_banco,ccc_sucursal,ccc_control,ccc_cuenta) {
	function __calculate_control(val) {
		var valores = new Array(1,2,4,8,5,10,9,7,3,6);
		var control = 0;
		for(var i=0;i<=9;i++) {
			control += parseInt(val.charAt(i)) * valores[i];
		}
		control = 11 - (control % 11);
		if(control==11) control = 0;
		else if (control==10) control = 1;
		return control;
	}
	var ccc = ccc_banco + ccc_sucursal + ccc_control + ccc_cuenta;
	if(!/^\d{20}$/.exec(ccc)) {
		return false;
	}
	return ccc_control == (__calculate_control("00"+ccc_banco+ccc_sucursal) + "" + __calculate_control(ccc_cuenta));
}

function check_key_domain(e) {
  k=(document.layers || !document.all)?e.which:e.keyCode;
  return k<32 || /[\-0-9a-zñàáèéíïòóúüçäëö\·\.\@]/i.test(String.fromCharCode(k))
}

function ChangeDomainInput(e) {
	$(e).val( $(e).val().toLowerCase().replace(/[^\-0-9a-zñàáèéíïòóúüçäëö\·\.]/gi,'') );
}

function check_domain_format(elem) {
	ChangeDomainInput(elem);
	var val = $(elem).val();
	if(val.length == '') {
		check_domain_alert();
		return false;
	}
	if(!/\./.test(val)) {
		val += '.es';
	}
	if(!check_domain(val)) {
		$(elem).focus();
		check_domain_alert();
		return false;
	}
	return true;
}


function check_domain(domain) {
	var val = domain.toLowerCase();
	return /^([a-z0-9àáèéíïòóúüäëöç\·ñ][a-z0-9àáèéíïòóúüäëöç\·ñ\-]*[a-z0-9àáèéíïòóúüäëöç\·ñ]?\.)*([a-z0-9àáèéíïòóúüäëöç\·ñ][a-z0-9àáèéíïòóúüäëöç\·ñ\-]*[a-z0-9àáèéíïòóúüäëöç\·ñ]\.)[a-z]{2,4}$/i.test(val);
}

function check_domain_alert() {
		var msg = "El nombre de dominio no es válido." + "\n" +
			"Indique un nombre de dominio, los caracteres permitidos son de la 'a' a la 'z', los dígitos del 0 al 9 y el guión - que no puede ser el primero ni último." + 
			"\n\n" + "No se permiten espacios en blanco, puntos, etc."+ "\n\n" +
			"No hay distinción entre minúsculas y mayúsculas, la longitud máxima son 64 caracteres y la mínima 3.";
		alert(msg);
}

function checkEmail(email) {
	var re = /^([a-z0-9\_\.\-])+@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+$/i;
	return re.test(email);
}

function checkIdentificacion(ident,type) {
	var t = type || 1;
	switch(parseInt(t)) {
		case 1: // DNI;
			return checkDNI(ident);
			break;
		case 2: // CIF;
			return checkCIF(ident);
			break;
		case 3: // NIE
			return checkNIE(ident);
			break;
	}
	return false;
}

function checkDNI(dni) {
	var re = /^\d{8}[a-z]$/i;
	if(!re.test(dni)) {
		return false;
	}
	var dni = dni.toUpperCase();
	var stack = 'TRWAGMYFPDXBNJZSQVHLCKE';
	var key = dni.charAt(8);
	var num = dni.substring(0,8)%23;
	return (key == stack.charAt(num)) ? true : false;
}

function checkNIE(nie) {
	var re = /^[XYZ]\d{8}[a-z]$/i;
	if(!re.test(nie)) {
		return false;
	}
	nie = nie.replace(/^x\d/i, '0').replace(/^y\d/i, '1').replace(/^z\d/i, '2');
	return checkDNI(nie);
}

function checkCIF(cif) {
	var re = /^[a-hjk-nmpqrsuvw][0-9]{7}[a-j0-9]$/i;
	var cif = cif.toUpperCase();
	if(re.test(cif)) {
		var sum = 0;
		for(var i=2;i<(cif.length-1);i+=2) {
			sum += parseInt(cif.charAt(i));
		}
		for(var i=1;i<(cif.length-1);i+=2) {
			var t =  parseInt(cif.charAt(i)) * 2;
			sum += (t>9) ? (t-9) : t;
		}
		var control = 10 - (sum%10);
		if(control==10) {
			control = 0;
		}
		var stack = 'JABCDEFGHI';
		var key = cif.charAt(8);
		return (key==stack.charAt(control) || parseInt(key)==control) ? true: false;
	}
	return false;
}

function checkPhone(phone,country) {
	var re = new RegExp('^\\+[0-9]{1,3}\\.[0-9]{9,12}$','gi');
	if(re.test(phone)) {
		return true;
	}
	if(country=='ES' && re.test('+34.' + phone)) {
		return true;
	}
	return false;
}

function check_ip(ip) {
	return /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3})$/.test(ip) ? true :false;
}
function check_key_ip(e) {
	k=(document.layers || !document.all)?e.which:e.keyCode;
	return k<32 || /[0-9\.]/i.test(String.fromCharCode(k))
}

/*============================================================
  Facebox popup 1.2
============================================================*/


(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()
 
    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }
 
  /*
	* Public, $.facebox methods
	*/
 
  $.extend($.facebox, {
    settings: {
      opacity : 0,
      overlay : true,
      loadingImage : '/facebox/loading.gif',
      closeImage : '/facebox/closelabel.gif',
      imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table class="gpopup"> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="footer"> \
                  <a href="#" class="close popup_close "></a> \
                  <a href="#" class="close popup_update"></a> \
                  <a href="#" class="close popup_print"></a> \
                </div> \
                <div class="content"> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },
 
    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()
 
      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')
 
      $('#facebox').css({
        top:  getPageScroll()[1] + (getPageHeight() / 10),
		  left: $(window).width() / 2 - ($('#facebox').width() / 2) // 385.5
      }).show()
 
      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },
 
    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
		/* HAck DD */
		$.facebox.ViewHeader();
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },
 
    close: function() {
      $(document).trigger('close.facebox')
      return false
    },
		Update: function(data,o) {
			o = $.extend({
					init: true,
					print: false,
					header: true,
					overclass: ''
					}, o || {});
			if(o.init) {
				$.facebox(data);
			}
			$.extend($.facebox.settings,{
				viewheader: o.header,
				viewprint: o.print,
				viewupdate: true
			});
			$('#facebox').removeClass();
			if(o.overclass.length>0) {
				$('#facebox').addClass(o.overclass);
			}
			$('#facebox .popup_update').show().unbind('click').click(function() {
				$.facebox.loading()
				if (data.ajax) fillFaceboxFromAjax(data.ajax)
				else if (data.image) fillFaceboxFromImage(data.image)
				else if (data.div) fillFaceboxFromHref(data.div)
				else if ($.isFunction(data)) data.call($)
				else $.facebox.reveal(data, klass)
				return false;
			});
		},
		ViewHeader: function() {
			function __ViewHeader(s,id) {
				if(typeof(s)=='boolean') {
					s ? $(id).show() : $(id).hide();
				}
			}
			__ViewHeader($.facebox.settings.viewheader,'#facebox .footer');
			__ViewHeader($.facebox.settings.viewprint,'#facebox a.popup_print');
			__ViewHeader($.facebox.settings.viewupdate,'#facebox a.popup_update');
		}
  })
 
  /*
	* Public, $.fn methods
	*/
 
  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return
 
    init(settings)
 
    function clickHandler() {
      $.facebox.loading(true)
 
      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]
 
      fillFaceboxFromHref(this.href, klass)
      return false
    }
 
    return this.bind('click.facebox', clickHandler)
  }
 
  /*
* Private methods
*/
 
  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true
 
    $(document).trigger('init.facebox')
    makeCompatible()
 
    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')
 
    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)
 
    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage
 
    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })
	 /* Hack DD */
    $('#facebox .close').not('.popup_close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
    $('#facebox .popup_close').click($.facebox.close)
	 $('#facebox .popup_print').click(function() {
			var pw = window.open('','popupimpr');
			pw.document.write($('#facebox .content').html());
			pw.document.close();
			pw.print();
			pw.close();
			return false;
	 });
  }
 
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {   // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }
 
  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {  // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }
 
  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings
 
    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }
 
  // Figures out what you want to display and displays it
  // formats are:
  // div: #id
  // image: blah.extension
  // ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), klass)
 
    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }
 
  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }
 
  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }
 
  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
  }
 
  function showOverlay() {
    if (skipOverlay()) return
 
    if ($('#facebox_overlay').length == 0)
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')
 
    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }
 
  function hideOverlay() {
    if (skipOverlay()) return
 
    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide")
      $("#facebox_overlay").remove()
    })
 
    return false
  }
 
  /*
	* Bindings
	*/
 
  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);
$.extend($.facebox.settings, {
	opacity: 0.25,
	loadingImage: '/images/css/facebox/loading.gif',
	closeImage: '/images/css/facebox/closelabel.gif'
});
$.extend($.facebox, {
	Reload: function() {
		$('#facebox .popup_update').click();
	},
	View: function(url,o) {
		return $.facebox.Update({ajax: url}, o);
	},
	Close: function() {
		$.facebox.close();
	},
	Aviso: function(url,o) {
		o = $.extend({ overclass: 'simple', header: false }, o || {});
		return $.facebox.View(url,o);
	},
	Init: function() {
		$('a.facebox_aviso').click(function() {
			$.facebox.View( $(this).attr('href').replace(/aviso/,'aviso/doc') , { print: true });
			return false;
		});
		$('a.facebox_href').unbind('click').click(function() {
			$.facebox.View( $(this).attr('href'), { print: true });
			return false;
		});
	}
});
function WhoIs(domain) {
	if(domain && domain.length>2) {
		$.facebox.View('/buscar_whois/?domain=' + encodeURIComponent(domain), { print: true});
	}
}
function PopupService(domain,isCesta,type,o) {
	if(domain && domain.length>2) {
		$.facebox.View('/api/dominios/servicetool/?domain=' + encodeURIComponent(domain) + (isCesta?'&iscc=1':'') + (type?'&type='+type:''), o);
	}
}
function Aviso(url,o) {
	$.facebox.Aviso(url,o);
}
function Popup(url,o) {
	o = $.extend({ header: true}, o || {});
	$.facebox.View(url,o);
}
function PopupAppend( html ) {
	$('#facebox .content').empty().DDLoading('remove').append( html );
}
function PopupInit() {
	return $('#facebox .content').DDLoading('remove');
}
function PopupLoading() {
	return $('#facebox .content').DDLoading('block');
}
function PopupPost( form ) {
	PopupLoading();
	$.ajax({
		url: $(form).attr('action'),
		type: 'POST',
		data: $(form).serialize(),
		success: function(html) {
			PopupInit();
			PopupAppend( html );
		}
	});
}
function PopupClose() {
	jQuery(document).trigger('close.facebox');
}

/*============================================================
  Cesta de Compra
============================================================*/

var CestaCompraAddCheck  = false;
var cestacompra = {
	obj: '#shopping_cart',
	cont: '#shopping_cart-cont',
	list: '#shopping_cart-cont ul:eq(0)',
	url: '/cestacompra/',
	init: false,
	STO: null,
	updated: false,
	showed: false,
	items: null,
	effects: 'normal',
	delay_time: 200, // ms
	create: function() {
		if(this.init) return;
		this.init = true;
		this.items = new Array();
		var myself = this;
		$(this.obj).bind('mouseenter',function() {
					myself.hover();
				}).bind('mouseleave',function() {
					myself.hover_out();
				});
	},
	del: function(url,service,f) {
		this.show('del='+ encodeURIComponent(url) + ((service) ? '&service=' + service : ''),true,f);
	},
	empty: function(url,f) {
		this.show('void=void',true,f);
	},
	changeservice: function(url,service,f) {
		this.show('change='+encodeURIComponent(url)+'&type='+service,true,f);
	},
	changecantidad: function(url,key,cant,f) {
		this.show('changecant='+encodeURIComponent(url)+'&key='+key+'&cant='+cant,true,f)
	},
	renew: function(url,force,f) {
		this.show('renew='+encodeURIComponent(url),force,f);
	},
	renewh: function(url,force,f) {
		this.show('renewh='+encodeURIComponent(url),force,f);
	},
	add: function(url,f) {
		this.show('add=' + encodeURIComponent(url),true,f);
	},
	view: function(f) {
		this.show('',true,f);
	},
	show: function(args,force,f) {
		if(!this.updated || (force)) {
			this.update(args,f);
		}
		if(!(force) && !this.showed) {
			this.showed = true;
			$(this.cont).slideDown(this.effects, function() {$('img',this).show()});
		}
		this.clearEvents();
	},
	unshow: function() {
		this.showed = false;
		$('img', this.cont).hide();
		$(this.cont).slideUp(this.effects);
		this.clearEvents();
	},
	hover_out: function() {
		this.clearEvents();
		if(this.showed) {
			var myself = this;
			if(typeof STO != 'undefined') this.STO = STO(function() { myself.unshow(); }, this.delay_time);
		}
	},
	hover: function() {
		this.clearEvents();
		if(!this.showed)  {
			var myself = this;
			if(typeof STO != 'undefined') this.STO = STO(function() { myself.show(); }, this.delay_time);
		}
	},
	clearEvents: function() {
		if(this.STO!=null) {
			clearTimeout(this.STO);
			this.STO = null;
		}
	},
	update: function(args,f) {
		this.updated = true;
		$(this.list).empty();
		$('<li><i>Cargando...</i></li>').appendTo(this.list);
		var myself = this;
		$.ajax({url: myself.url, data: args, dataType: 'xml', success: function(xml) { myself.xml2data(xml); if(f) {f(xml);}}});
	},
	xml2data: function(xml) {
		if(!xml) return;
		$(this.list).empty();
		this.items = new Array();
		this.length = parseInt($('length',xml).text());
		var action = $('action',xml).text();
		if($('errormsg',xml).length>0) {
			var aErrors = [];
			$('errormsg',xml).each(function() { aErrors.push($(this).text()); });
			alert(aErrors.join("\n"));
		} else if(!/shopping_cart/i.test(document.location) && /^(renew|add)/i.test(action)) {
			if($.cookie('__' + action)!='1') {
				PopupService( $('action',xml).attr('url'), false, 'message'+action);
			}
		}
		var s = $(this.obj + ' a').text(this.length + ' productos en Carrito');
		if(this.length>0) {
			var myself = this;
			$('item',xml).each( function(i) {
				var url = $('url',this).text();
				var li = $('<li>' + url + '<ul></ul></li>').appendTo(myself.list);
				myself.items.push($('idn_domain',this).text());
				$('service',this).each( function(i) { $('<li>'+ $('desc',this).text() + '</li>').appendTo(li.find('ul')); });
			});
		} else {
			$('<li>Sin Productos</li>').appendTo(this.list);
		}
		this.repaintsearch();
	},
	inCesta: function(url) {
		for(var i=0;i<this.items.length;i++) {
			if(url == this.items[i]) {
				return true;
			}
		}
		return false;
	},
	repaintsearch: function() {
		this.create();
		if(!this.updated) {
			this.update();
			return;
		}
		var myself = this;
		var ids = new Array();
		$('#buscar_table div.busqueda').each( function() { ids.push($(this).attr('id')) });
		$('#table_diccionarios table:first tbody tr').each(function() { ids.push($(this).attr('id')); });
		$.each(ids,function(i,n) {
			var inCesta = myself.inCesta(n);
			var td = $(DDDomain2Id(n) + ' .busqueda_carrito');
			var elem = td.find('a:first');
			if(elem.hasClass('carrito') || elem.hasClass('carritoa')) {
				if(inCesta) {
					elem.removeClass('carrito').
						addClass('carritoa').
						attr('title','Añadido al carrito de Compra').
						attr('onclick','').
						text('Añadido').
						click(function() { alert('Ya se ha añadido al carrito');return false; });
				}
			}
		});
	}
};

function AnadirAlCarrito(domain,elem,comprobar,f)
{
	var aDomains = typeof(domain)=='string' ? new Array(domain) : domain;
	var comprobar = typeof(comprobar)=='boolean' ? comprobar : CestaCompraAddCheck;
	$(elem).html('Añadiendo...');
	if(comprobar) {
		$.ajax({
			url: '/api/dominios/search/',
			data: 'domains=' + aDomains.join(','),
			dataType: 'xml',
			success: function(xml) {
				$('domain',xml).each(function() {
					var name = $('name',this).text();
					var available = $('status',this).attr('s')=='1';
					if(available) {
						cestacompra.add(domain);
						return;
					}
					alert('No se ha podido añadir el dominio a la cesta de compra' + "\n" +'Motivo: ' + $('message',this).text());
				});
			}
		});
	} else {
		cestacompra.add(domain,f);
	}
	return false;
}

/*============================================================
  Funciones de Busqueda de dominios
============================================================*/

var DDBuscarProgressTimeout = 50;
var DDBuscarCategorias = [];
var __DDSearchCache = new Array();
var __DDSearchCategoryActive = null;
var DDCacheInfoProd = new Array();

var preloadImg = [ 'buscar_disponible2.gif', 'buscar_nodisponible2.gif', 'buscando.gif', 'buscando2.gif', 'buscando3.gif', 'x.gif', 'v.gif', 'w.gif' ];
for(var k in preloadImg) {
	var img = new Image();
	img.src = '/images/' + preloadImg[k];
	preloadImg[k] = img;
}

function DDSearchDomainInit()
{
	if(!DDBuscarCategorias) {
		DDBuscarCategorias = [];
	}
	DDBuscarProgressTimeout = 50;
	__DDSearchCache = new Array();
	__DDSearchCategoryActive = null;
}

function DDSearchCategory( keyword, title, tlds ) {
	this.keyword = keyword;
	this.title = title;
	this.tlds = typeof(tlds)=='string' ? tlds.split('|') : tlds;
	this.isAlternateCat = function(cat) {
		return ( new RegExp('^' + cat + '_[a-z]+$', 'i') ).test( this.keyword );
	};
	this.AppendToCache = function() {
		DDBuscarCategorias[ this.keyword ] = this;
		return this;
	};
	return this;
}

function DDSearchDomain(node,InitUpdate) {
	this.name = '';
	this.tld = '';
	this.idnname = '';
	this.available = false;
	this.message = '';
	this.next_action = '';
	this.price = '';
	this.premium = false;
	this.inpromotion = false;
	if(typeof(node)=='string') {
		this.idnname = node;
	} else {
		this.name = $('name',node).text();
		this.tld = $('tld',node).text();
		this.idnname = $('name',node).attr('idn');
		this.available = $('status',node).attr('s')==1;
		this.message = $('status',node).text();
		this.next_action = $('status',node).attr('n');
		this.price = $('status',node).attr('p');
		this.premium = $('name', node).attr('premium')==1;
		this.inpromotion = $('name', node).attr('promotion') == '1';
	}
	this.Update = function(type) {
		var row = $(DDDomain2Id(this.idnname));
		row.stop().
			removeClass('busquedanodisponible').
			removeClass('busquedadisponible').
			removeClass('busquedaloading');
		row.children().not('.busqueda_name, .busqueda_status, .busqueda_extra').hide();
		var sts = row.find('.busqueda_status').empty();
		var extra = row.find('.busqueda_extra').empty();
		var btn = row.find('.busqueda_carrito').empty();
		var info = row.find('.busqueda_info').empty();
		if(type=='loading') {
			row.addClass('busquedaloading');
			sts.append('<img src="/images/buscando3.gif" alt="Buscando" /> <span class="info">Buscando</span>');
			return this;
		}

		var pricestr = '€/año';
		var priceclass = 'c_info';

		if(this.premium) {
			extra.append('<a class="premium" href="/contacto/" title="Dominio premium" onclick="return false;"><img src="/images/premium.gif" alt="" /> Premium</a>');
			pricestr = '€';
		} else if( this.inpromotion ) {
			extra.append('<a class="premium" href="/promo/" title="Ofertas" onclick="return false;"><img src="/images/premium.gif" alt="" /> En oferta</a>');
			priceclass = 'c_verde';
		}
		switch(this.next_action) {
			case 'error':
				row.addClass('busquedanodisponible');
				row.find('.busqueda_error').show().html('<span class="c_rojo">' + this.message + '</span>');
				if(!/(Nombre de dominio no permitido|no permite dominios IDN|Sintaxis incorrecta|IDN permitidos|Permitted IDN|allow IDN domains)/i.exec(this.message) ) {
					sts.append('<img src="/images/w.gif" alt="" /> <span class="c_rojo">Error</span>');
					extra.append('<a href="#" title="Reintentar" onclick="DDBuscarDominios(\'' + this.idnname + '\');return false;">'+
							'<img src="/images/update.gif" alt="" /> Reintentar</a>');
				} else {
					sts.append('<img src="/images/x.gif" alt="" /> <span class="c_rojo">Error</span>');
				}
				break;
			case 'reserved':
				row.addClass('busquedanodisponible');
				sts.append('<img src="/images/x.gif" alt="" /> <span class="c_rojo">Palabra reservada</span>');
				row.find('.busqueda_error').show().html('<span class="c_rojo">' + this.message + '</span>');
				if(!this.premium) {
					extra.append('<a href="' + DDBuscarReservedWordLink(this.name) + '" class="miniwhois" target="_blank">Información</a>');
				}
				break;
			default:
				if( this.available ) {
					row.addClass('busquedadisponible');
					sts.append('<img src="/images/v.gif" alt="" /> <span class="c_verde">Disponible</span>');
					if(this.next_action=='contactar') {
						btn.show().
							append('<a class="carritocontactar" title="Contactar" href="/contacto/">Contactar</a>');
					} else {
						btn.show().
							append('<a class="carrito" title"=Añadir al carrito" href="#" onclick="AnadirAlCarrito(\'' + 
								this.idnname + '\', this); return false;">Añadir al carrito</a>');
					}
					info.show().
						append('<a class="miniinfo" href="/tarifas/">&nbsp;</a>').
						append('<a class="'+priceclass+'" href="/tarifas/" title="Consultar tarifas">' + this.price + ' ' + pricestr +  '</a>');
				} else {
					row.addClass('busquedanodisponible');
					sts.append('<img src="/images/x.gif" alt="" /> <span class="c_rojo">No disponible</span>');
					btn.show().
						append('<a class="transferir" title="Transferir el dominio" href="/transfer/?domain=' + this.name +'">Transferir dominio</a>');
					info.show().
						append('<a class="miniinfo" href="/tarifas/">&nbsp;</a>').
						append('<a class="miniwhois" href="#" onclick="WhoIs(\'' + this.idnname + '\');return false;">WhoIs</a>').
						append('&nbsp;&nbsp;&nbsp;').
						append('<a class="verweb" title="Ver Web" href="http://www.' + this.name + '/" target="_blank">Ver Web</a>');
				}
				var tld = this.tld;
				info.find('.miniinfo').
					click(function() { return false; }).
					bind('mouseenter', function() {
						$(this).CacheInfoProd( tld );
					}).bind('mouseleave',function() {
						$.ToolTip().Hide();
					});
				break;
		}
		return this;
	};
	if(InitUpdate) {
		return this.Update();
	}
	return this;
}

function DDDomain2Id(domain) {
	return '#' + Domain2jquery(domain);
}

function DDBuscarReservedWordLink(name) {
	var reserved = [
		[ /.es$/,	"https://www.nic.es/normativa/index.html" ],
		[ /.me$/, 	"http://www.domain.me/index.php?page=6" ],
		[ /.info$/,	"http://www.icann.org/tlds/agreements/info/appendix-06-08dec06.htm" ],
		[ /.asia$/,	"http://www.registry.asia/" ],
		[ /.fr$/,	"http://www.afnic.fr/obtenir/chartes/fondamentaux_en" ],
		[ /.ca$/,	"http://www.dot.ca" ],
		[ /.de$/,	"http://www.denic.de" ]
	];
	for(var i in reserved) {
		if(reserved[i][0].test(name)) return reserved[i][1];
	}
	return '/contacto/';
}
function DDBuscarDominios(ids,uc) {
	var useCache = uc || false;
	if(typeof(ids)=='string') {
		ids = new Array(ids);
	}
	if(ids.length==0) { return; }
	var domains = new Array();
	for(var i=0;i<ids.length;i++) {
		var name = ids[i];
		var keyname = '#' + name;
		if(useCache) {
			if(typeof(__DDSearchCache[keyname])=='object') {
				__DDSearchCache[keyname].Update();
				continue;
			}
			if(typeof(__DDSearchCache[keyname])!='undefined') {
				continue;
			}
		}
		__DDSearchCache[keyname] = '';
		DDSearchDomain( name ).Update('loading');
		domains.push(name);
	}
	if(domains.length) {
		$.ajax({
			url: '/api/dominios/search/',
			data: 'domains=' + domains.join(','),
			dataType: 'xml',
			success: function(xml) {
				DDBuscarDominiosAjax(xml, useCache);
			}
		});
	}
}

function DDBuscarDominiosAjax(xml,useCache)
{
	if(!xml) { return; }
	
	var id = $('search',xml).attr('id');
	var st = $('search',xml).attr('status');
	
	
	$('domain',xml).each( function()  {
		var d = new DDSearchDomain(this,false);
		var name = DDDomain2Id(d.idnname);
		if($(name+'.busquedaloading').length) {
			d.Update();
		}
		if(useCache) {
			var name = '#' + d.idnname;
			if(typeof(__DDSearchCache[name])!='object') {
				__DDSearchCache[name] = d;
			}
		}
	});
	
	cestacompra.repaintsearch();

	if(st=='error') {
		if(typeof(__DDSearchCategoryActive)=='string') {
			$('div.busqueda.busquedaloading.busqueda_categoria_'+ __DDSearchCategoryActive).each(function() {
					var d = new DDSearchDomain(false,false);
					d.idnname = $(this).attr('id');
					d.next_action = 'error';
					d.message = 'Error de conexión';
					d.Update();
			});
		}
	} else if(st!='ok') {
		if(DDBuscarProgressTimeout<600) {
			DDBuscarProgressTimeout *= 2;
		}
		STO(function() {
				$.ajax({
				url: '/api/dominios/search/',
				data: {id: id},
				dataType: 'xml',
				success: function(xml) { DDBuscarDominiosAjax(xml,useCache); }
			});
		}, DDBuscarProgressTimeout);
	}
}

/*============================================================
  Generación de datos y obtención
============================================================*/

function ErrorEnForm(id) {
	$(id).DDFormError();
}
function NoErrorEnForm(id) {
	$(id).DDFormErrorClean();
}

function ErroresEnForm(aData) {
	if(aData.length>0) {
		$(function() {
			$('#' + aData.join(', #')).DDFormError();
		});
	}
}

function generate_password(l,frmPW,frmPWRepeat,frmPWGen) {
	var length = l || 6;
	$.ajax({url: '/info/password/',data: 'l='+length,dataType: 'xml',
		success: function(xml) {
			var pass = $('password',xml).text();
			$('#'+frmPW).val(pass);
			$('#'+frmPWRepeat).val(pass);
			$('#'+frmPWGen).html(pass);
		}
	});
}

function DDAcceptTransfer(domain)
{
	$.facebox.View('/api/dominios/tplaccepttransfers/?domain=' + encodeURIComponent(domain));
}

function change_label(label,domain,f) {
	$.ajax({
		url: '/api/dominios/editlabel/',
		data: {domain: domain, label: label},
		dataType: 'xml',
		success: function(xml) {
			var errors = false;
			if($('error',xml).length>0) {
				$('error',xml).each(function() { alert( $(this).text() ) });
				errors = true;
			}
			if($.isFunction(f)) {
				f(xml,errors);
			}
		}
	});
}
function change_comentario(comment,domain,f) {
	$.ajax({
		url: '/api/dominios/editcomment/',
		data: { domain: domain, comment: comment },
		dataType: 'xml',
		success: function(xml) {
			var errors = false;
			if($('error',xml).length>0) {
				$('error',xml).each(function() { alert($(this).text()); });
				errors = true;
			}
			if($.isFunction(f)) {
				f(xml,errors);
			}
		}
	});
};
function change_autorenew(domain,isReg,active,f)
{
	$.ajax({
		url: '/api/dominios/autorenew/',
		data: { domain: domain, isreg: isReg?'registro':'hosting', active: typeof(active)=='boolean' ? (active?1:0) : -1 },
		dataType: 'xml',
		success: function(xml) {
			var errors = false;
			if($('errors',xml).length>0) {
				$('error',xml).each(function() { alert($(this).text()); });
				errors = true;
			}
			if($.isFunction(f)) {
				f(xml,isReg,errors);
			}
		}
	});
}

function Adsense4Domains(domain) {
	var msg = "Para asignar 'Google Adsense para dominios' se deben modifica toda la zona DNS." +
		"\n" +
		"También debes tener asignado nuestros servidores DNS al dominio " + domain + " para que la configuración DNS sea aplicada de forma correcta." +
		"\n\n" + 
		"Además, necesitaras tu ID de Adsense (que encontrarás en la configuración de Google Adsense)." + 
		"\n" +
		"La configuración que se va a aplicar, puede tardar hasta 48 horas en estar disponible en Internet."+
		"\n\n" +
		"Indica tu ID de Adsense y pulsa 'Aceptar' para asignar el parking de Google Adsense, o cancelar en caso contrario.";
	var message = prompt(msg);
	if(message==null) return false;
	if(message.length==0 || typeof(message)=='undefined' || message=='undefined') {
		alert('Debes indicar el ID Adsense, lo puedes encontrar en la página de configuración de Google Adsense');
	} else if(!/^[a-z0-9\_]{1,50}$/i.test(message)) {
		alert('El ID Adsense no parece correcto');
	} else {
		redirect('/admin/misdominios/'+domain+'/service/dns/?adsense=1&adsense_id=' + message);
	}
	return false;
}

/*============================================================
  Ordenación y paginación
============================================================*/

function Ordenar(f,col,ord,isAjax)
{
	$(f).children('input[name="page_filter"]').val(0);
	$(f).children('input[name="order_filter"]').val(col);
	$(f).children('input[name="order_type_filter"]').val(ord=='1'?'ASC':'DESC');
	return PaginaSendForm(f,isAjax);
}
function Posterior(f,isAjax) { // no utilizado
	var page = $(f).children('input[name="page_filter"]').val();
	return Pagina(f,page+1,isAjax);
}
function Anterior(f,isAjax) { // no utilizado
	var page = $(f).children('input[name="page_filter"]').val();
	return Pagina(f,page-1,isAjax);
}
function Pagina(f,page,isAjax) {
	$(f).children('input[name="page_filter"]').val(page);
	return PaginaSendForm(f,isAjax);
}
function Filtrar(f,isAjax) {
	return Pagina(f,0,isAjax);
}
function Export2File(f,type) {
	return PaginaSendForm(f,false,type);
}
function Export2FileURL(url,type) {
	var id = '__export_form_tmp_' + (new Date()).getTime();
	$('<form method="POST" name="'+id+'" id="'+id+'" action="'+url+'"></form>').appendTo('body');
	var r = Export2File('#'+id,type);
	$('#' + id ).remove();
	return r;
}
function AddDivCargando(elem,t)
{
	var text = t || "Cargando datos..."
	var div = $('<div class="cargando">'+text+'</div>').css({opacity:0.95});
	if(elem) {
		div.appendTo($(elem).css({ position: 'relative' }));
	}
	return div;
}
function DeleteDivCargando(elem) {
	$('div.cargando',$(elem)).remove();
}
function PaginaSendForm(f,ia,type)
{
	var t = type || '';
	var __isAjax = ia || false;
	var id = '__export_input_type_id';
	var ExportMethod = false;
	if(typeof(t)=='string' && t.length>0) {
		$('<input type="hidden" name="export" id="'+id+'" value="'+t+'" />').appendTo(f);
		ExportMethod = t;
	}
	if(__isAjax != false) {
		var urls = $(f).attr('action');
		var datas = $(f).serialize();
		SaveSearchData(datas);
		if(typeof(__isAjax) == 'string') {
			AddDivCargando(__isAjax);
			$.ajax({ url: urls, data: datas + '&is_ajax_filter=is_ajax', type:'POST', success: function(txt) {
				$(__isAjax).html(txt);
				if(typeof(__graph_cache)!='undefined') {
					var a = __graph_cache;
					__graph_cache = new Array();
					for(var i=0;i<a.length;i++) {
						Export2Graph(a[i][0],a[i][1],a[i][2]);
					}
				}
				return false;
			}});
		} else {
			$.facebox.View(urls + (urls.indexOf('?')==-1 ? '?':'')+'&'+datas); 
		}
	} else {
		var VisualExportMethod = !(isBrowserIE() && ExportMethod);
		if(VisualExportMethod && $(f).find('div.__export_link__').length) {
			var __iframe_temp = $(f).find('div.__export_link__:first').parent();
			__iframe_temp.children().hide();
			__iframe_temp.append('<strong>Exportando datos...</strong>');
			__iframe_temp.children('iframe').remove();
			var iframe = $('<iframe class="__iframe_export_link__" src="' + $(f).attr('action') + '?' + $(f).serialize() + '" style="display:none" ></iframe>').
				load(function() {
					__iframe_temp.children('strong').remove();
					__iframe_temp.children().not('iframe').show();
				}).
				appendTo(__iframe_temp);
		} else {
			$(f).submit();
		}
	}
	if(ExportMethod) {
		$('#'+id).remove();
	}
	return false;
}
var __graph_cache = new Array();
function Export2Graph(f,img,extra_args) {
	var args = extra_args || '';
	var url = $(f).attr('action');
	url += (url.indexOf('?')==-1 ? '?' : '') + '&' + $(f).serialize() + '&export=graph&'+args+'&nocache='+(new Date()).getTime();
	__graph_cache.push([f,img,args]);
	var __i = new Image();
	__i.src = url;
	$(__i).load( function() { $(img).attr('src',url).attr('alt','Gráfico'); }).
		error( function() { $(this).attr('alt','Fallo de conexión'); });
	return false;
}
function ResetFilters(f,isAjax) {
	$(f).find('input:text').val('');
	$(f).find('select').each(function() {
		if($(this).attr('name')!='limit_filter') {
			$('option:selected',this).attr('selected',false);
			$('option:first',this).attr('selected',true);
		}
	});
	return PaginaSendForm(f,isAjax);
}
var __save_searchs = false;
var __save_searchs_cookie = 'savesearch';
function SaveSearches() {
	__save_searchs = true;
}
function SaveSearchData(data)
{
	if(!__save_searchs) return;
	$.cookie(__save_searchs_cookie,data);
}


/*============================================================
  Interacción
============================================================*/

function LinkMostrarOcultar(e,o) {
	var ocultar = typeof(o)=='undefined' ?  $(e).html()=='Mostrar' : o;
	if(ocultar) {
		$(e).removeClass('mostrar').attr('title','Ocultar').html('Ocultar');
	} else {
		$(e).addClass('mostrar').attr('title','Mostrar').html('Mostrar');
	}
	return ocultar;
}

function ObtainIP(name,f) {
	$.ajax({url:'/info/resolvip/',data:'host='+name,dataType:'xml',success: function(xml) { f($('ip',xml).text()) }});
}

function comunicado_extended(elem,id) {
	ToggleTrExtended($(elem).parent().parent(),'divcomunic_'+id,' class="comunicados"');
	var div = '#divcomunic_'+id;
	if($.trim($(div).html())=='') {
		$(div).DDLoading('inline');
		$.get('/info/comunicados/',{format:'html',id:id},function(data) { $(div).html(data) });
	}
}

function historial_extended(elem,hist_id,where) {
	var divid = 'historial_extended_' + where + '_' + hist_id;
	var div = '#' + divid;;
	ToggleTrExtended($(elem).parent().parent(),divid,' class="historial"');
	if($.trim($(div).html())=='') {
		$(div).DDLoading('inline');
		$.get('/info/historial_extended/',{ id: hist_id, format: 'html', where: where },function(data) {$(div).html(data)});
	}
}

function ToggleTrExtended(elem,id,html) {
	if($('#'+id).length==0) {
		$('<tr><td colspan="'+$('td',elem).length+'"><div id="'+id+'" '+ (html || '') + '></div></td></td>').hide().insertAfter(elem);
		$('#'+id).hide();
	}
	if($('#'+id).css('display')!='none') {
		$('#'+id).hide('fast',function() { $(this).parent().parent().hide(); });
	} else {
		$('#'+id).parent().parent().show();
		$('#'+id).show('normal');
	}
}

function expandir_tickets(expandir) {
	var visible = !expandir;
	$('.ticketbody').each(function() {
		var linkid = '#'+ $(this).attr('id') + '_link';
		if(visible) {
			$(this).slideUp('normal');
			LinkMostrarOcultar(linkid,false);
		} else {
			$(this).slideDown('normal');
			LinkMostrarOcultar(linkid,true);
		}
	});
}

function toggle_ticket(id) {
	var linkid = id + '_link';
	$(id).slideToggle('normal');
	LinkMostrarOcultar(linkid);
}

function submit_zona_edicion_cargando(id,show)
{
	var p = $(id).find('p.__submit_zona__');
	p.find('span.__submit_zona__').remove();
	if(!show) {
		p.find('input').hide();
		p.append('<span class="c_gris __submit_zona__">Modificando datos...</span>');
	} else {
		p.find('input').show();
	}
}

function submit_zona_edicion(id,type,f)
{
	function __submit_zona_edicion_error(msg) {
		alert(msg);
	}
	var formid = '#form_' + type + '_' + id;
	var url = $('#form_' + type + '_' + id).attr('action');
	submit_zona_edicion_cargando(formid,false);
	$.ajax({
		url: url,
		data: $(formid).serialize(),
		dataType: 'xml',
		type: 'POST',
		success: function (xml) {
			submit_zona_edicion_cargando(formid,true);
			if(!xml) { submit_zona_edicion_error('Fallo de conexión'); return;};
			var hay_errores = false;
			$('error',xml).each( function() {
				__submit_zona_edicion_error($(this).text());
				hay_errores = true;
			});
			if(hay_errores) {
				return;
			}
			f(xml,'#tr_'+type+'_'+id,'#tr_'+type+'2_'+id);
			eliminar_zona_edicion(id,type);
		}
	});
}
function eliminar_zona_edicion(id,type) {
	$('#tr_' + type + '3_' + id).remove();
}
function insertar_zona_edicion(id,type,url)
{
	if($('#tr_'+type+'3_'+id).length==0) {
		$.ajax({url: url,data: 'id='+id,type: 'POST', success: function(data) {
				$('<tr id="tr_'+type+'3_'+id+'"><td colspan="'+$('#tr_'+type+'2_'+id+' td:first').attr('colspan')+'">'+ data+'</td></tr>').insertAfter('#tr_'+type+'2_'+id);
			}
		});
	} else {
		$('#tr_'+type+'3_'+id).toggle();
	}
}
function zona_edicion_comentario(xml,tr2) {
	var comentario = $('comentario',xml).text();
	$(tr2 + ' td:first div').html('Comentario: '+comentario);
	$(tr2).css('display',comentario.length>0?'':'none');
}

function confirm_delete(elem,form,msg) {
	if(confirm(msg)) {
		if(!isBrowserMozilla()) {
			$('<input type="hidden" name="'+$(elem).attr('name')+'" value="'+$(elem).val()+'" />').appendTo(form);
		}
		return true;
	}
	return false;
}

function AddGraphTr(link,url,id,force_load)
{
	var e = $('#tr_graph' + Domain2jquery(id));
	var fl = force_load || false;
	if(fl) {
		e.empty().remove();
	}
	if(!e.toggle().length) {
		var tr = $(link).parent().parent();
		var ntr = $('<tr id="tr_graph'+id+'"><td colspan="'+$('td',tr).length+'"><span class="c_gris">Cargando...</span></td></tr>').insertAfter(tr);
		$('<img src="'+url+'" alt="Gráfico" style="margin: 0 auto;" />').
			load(function() { $('span',$(this).parent()).remove(); $(this).fadeIn('slow');}).
			error(function() { $('span',$(this).parent()).text('Sin datos'); }).
			hide().
			appendTo($('td',ntr));
	}
}

function XMLAlerts2Div(xml,o) {
	o = $.extend({ tag_error: 'error', tag_inform: 'inform', view_informs: false, view_errors: true, alerts: true, append_errors: false, append_informs: true }, o || {});
	var se = '', si = '', s='';
	if(o.append_errors) {
		$(o.tag_error,xml).each(function() { se += '<p>' + $(this).text() + '</p>'; });
	}
	if(se.length) {
		s += '<div class="error_messages">' + se + '</div>';
	}
	if(o.append_informs) {
		$(o.tag_inform,xml).each(function() { si += '<p>' + $(this).text() + '</p>'; });
	}
	if(si.length) {
		s += '<div class="inform_messages">' + si + '</div>';
	}
	return s.length ? $(s) : $('<div></div>');
}

function XMLAlertsFast( xml, o ) {
	o = $.extend( { view_informs: false }, o || {});
	return XMLAlerts( xml, o );
}

function XMLAlerts(xml,o) {
	o = $.extend({
				tag_error: 'error',
				tag_inform: 'inform',
				view_informs: true,
				view_errors: true,
				alerts: true
			}, o || {});
	var ok = false;
	var aMessages = new Array();
	$(o.tag_error,xml).each(function() {
		if(o.view_errors) {
			aMessages.push($(this).text());
		}
	});
	$(o.tag_inform,xml).each(function() {
		if(o.view_informs) {
			aMessages.push($(this).text());
		}
		ok = true;
	});
	if(aMessages.length>0 && o.alerts) {
		alert(aMessages.join("\n"));
	}
	return ok;
}

function RestartTransferProcess(domain,url_redir,cancel,elem)
{
	var action = cancel ? 'transfercancel' : 'transferrestart';
	if(cancel) {
		if(!confirm('¿Estás seguro?')) {
			return;
		}
		$('<span class="c_gris f_small">Cancelando...</span>').insertAfter( $(elem).hide() );
	}
	$.ajax({
		url: '/api/dominios/' + action,
		dataType: 'xml',
		data: {domain: domain},
		success: function(xml) {
			if(XMLAlerts(xml)) {
				if(url_redir) redirect(url_redir);
			}
			if(cancel) {
				$(elem).show().next().remove();
			}
		}
	});
}

/*============================================================
  Contactos y Clientes
============================================================*/

function contact_mouseover(elem) {
	$('span:first',$(elem).parent()).html($('img:first',elem).attr('alt'));
}
function contact_mouseout(elem) {
	$('span:first',$(elem).parent()).html('');
}

var Contacto = function(data) {
	var params = data || {};
	params.classtype = 'contact';
	var el = new Cliente(params);
	el.types = ['registrant','admin','billing','tech'];
	el.Borrar = function() {
		return new Contacto({type:this.type}).toTemplate();
	};
	el.Editar = function(editar) {
		if(editar) {
			$('#copyfrom'+this.type).val('edit');
			$('#fieldset'+this.type+'_edit').show();
			$('#fieldset'+this.type+'_look').hide();
		} else {
			$('#copyfrom'+this.type).val('registrant');
			$('#fieldset'+this.type+'_edit').hide();
			$('#fieldset'+this.type+'_look').show();
		}
		if($.isFunction(__ContactEditarPost)) {
			__ContactEditarPost(this.type,editar);
		}
		return this;
	};
	el.RellenarContacto = function(nick) {
		var myself = this;
		$.ajax({url:'/info/datafromdomain/',data:{nick:nick},dataType:'xml',success:function(xml){ myself.fromXML(xml).toTemplate(); }});
		return this;
	};
	el.RellenarCliente = function() {
		var myself = this;
		$.ajax({url:'/info/mydata/',dataType:'xml',success:function(xml) { myself.fromXML(xml).toTemplate(); }});
		return this;
	};
	el.MisContactos = function() {
		$.facebox.View('/admin/micuenta/miscontactos/?type=' + this.type + '&popup=popup');
		return this;
	};
	el.CopyContact = function(type) {
		return this.Copy( Contacto({type: type}).fromTemplate() ).toTemplate();
	};
	el.RellenarDominio = function(domain) {
		$.each(this.types,function(i,n) {
			$.ajax({url:'/info/datafromdomain/',data:{domainid:domain,type:n},dataType:'xml',success:function(xml){
				Contacto({type:n}).fromXML(xml).toTemplate().Editar(true);
			}});
		});
		return this;
	};
	el.Whois = function(url) {
		var myself = this;
		$.ajax({ url: '/info/fromwhois/', data: 'domain='+url, dataType: 'xml', success: function(xml) {
			if(!xml) { return; }
			var sts = $('status',xml).text();
			switch(sts) {
				case 'exists':
					$.each(myself.types,function(i,n) {
						Contacto({type:n}).fromXML($(n,xml)).toTemplate().Editar(true);
					});
					var elem = $('#button_generar');
					if(elem.length>0) {
						for(var i=0; i<7; i++) {
							var name = $.trim($('dns:eq('+i+') name:first',xml).text()).toLowerCase();
							var inputid = '#dns' + (i+1);
							if($(inputid).length==0) {
								elem.click();
							}
							$(inputid).val(name);
						}
					}
					break;
				case 'tlderror': alert("No es posible la obtención de datos desde el WhoIs de dominios" + ' .'+ $('tld',xml).text()); break;
				case 'keyerror': alert("Aún no está implementado la obtención de datos desde el Whois: "+ $('whois_server',xml).text()); break;
				case 'urlerror': alert($('error',xml).text()); break;
				case 'noexists': alert('El dominio '+$('domain',xml).text()+" no existe, puedes comprarlo directamente"); break;
				case 'block':
					var domain = $('domain',xml).text();
					alert('El dominio '+domain+' tiene bloqueada su transferencia.' + "\n" +
							"Debes ir al Agente Registrador del dominio para desbloquearlo antes de poder transferirlo a DonDominio.com.");
					break;
			}
		}});
	};
	el.ContactCheck = function(title) {
		var copyfrom = $('#copyfrom'+this.type).val() || 'edit';
		if(copyfrom!='edit') return true;
		return this.fromTemplate().Check({},"\n" + "Errores en" + ' ' +title+":\n");
	};
	return el;
}

var Cliente = function(data) {
	var params = data || {};
	this.classtype = params.classtype || 'cliente';
	this.type = params.type || '';
	this.isorg = params.isorg || false;
	this.first_name = params.first_name || '';
	this.last_name = params.last_name || '';
	this.email = params.email || '';
	this.email_repeat = params.email_repeat || '';
	this.phone = params.phone || '';
	this.fax = params.fax || '';
	this.org_name = params.org_name || '';
	this.org_type = params.org_type || 1;
	this.ident_type = params.ident_type || 1;
	this.ident = params.ident || '';
	this.address = params.address || '';
	this.city = params.city || '';
	this.state = params.state || '';
	this.postal_code = params.postal_code || '';
	this.country = params.country || 'ES';
	this.__nic = params.__nic || '';
	this.isCliente = function() { return this.classtype=='cliente'; };
	this.isContacto = function() { return this.classtype=='contact'; };
	if(this.isCliente()) {
		this.user_name = params.user_name || '';
		this.password = params.password || '';
		this.password_repeat = params.password_repeat || '';
		this.activo = params.activo!='undefined' ? params.activo : true;
		this.facturable = params.facturable!='undefined' ? params.facturable : 1;
		this.auto_renew_permited = params.auto_renew_permited!='undefined' ? params.auto_renew_permited : 2;
		this.iva = params.iva!='undefined' ? params.iva : 0.18;
	}
	this.__set_val = function(id,val) { $(id+this.type).val(val); };
	this.__set_attr = function(id,attr,val) { $(id+this.type).attr(attr,val); };
	this.__default_val = function(id,default_value){return $(id+this.type).length>0?$(id + this.type).val() : (default_value || ''); };
	this.__default_attr = function(id,attr,default_value) {
		if($(id + this.type).length>0) { var a = $(id+this.type).attr(attr); return a=='undefined' ? (default_value || '') : a; }
		return (default_value || '');
	};
	this.Check = function(data,message_title) {
		var aErrors = new Array();
		var aOk = new Array();
		var aMess = new Array();
		var params = data || {};
		var ignore = params.ignore || [];
		var title = message_title || '';
		function __CheckCond(id) { for(var i=0;i<ignore.length;i++) { if(ignore[i]==id) return false; } return true; }
		function __Condition(cond,id,msg) {
			var cond_ignore = id;
			if(cond_ignore=='password_repeat') { cond_ignore = 'password'; }
			if(__CheckCond(cond_ignore)) {
				var message = msg || null; if(cond) { aErrors.push('#'+id); if(message!=null) { aMess.push(" - " + message); } } else { aOk.push('#'+id); }
			}
		}
		if(this.isCliente()) {
			__Condition(this.user_name.length<3,'user_name','Debes rellenar el login de usuario.');
			if(this.check_password) {
				__Condition(this.password.length<6,'password','La contraseña debe tener al menos 6 carácteres');
				__Condition(this.password.length>20,'password',"La contraseña no debe tener más de 20 carácteres");
				__Condition(this.password!=this.password_repeat,'password','Las constraseñas deben ser iguales');
				__Condition(this.password!=this.password_repeat,'password_repeat');
			}
		}
		__Condition(this.first_name.length<2,'first_name','Debes rellenar el nombre');
		__Condition(this.last_name.length<3,'last_name',"Debes rellenar los apellidos");
		__Condition(this.isorg && this.org_name.length<3,'org_name','Debes poner el nombre de la organización/empresa');
		__Condition(this.isorg && this.org_type == '1','org_type','Debes poner la forma jurídica de la empresa');
		__Condition(this.email.length==0,'email',"Debes rellenar el correo electrónico");
		__Condition(this.email!=this.email_repeat,'email','Los correo electrónicos deben ser iguales');
		__Condition(this.email!=this.email_repeat,'email_repeat');
		__Condition(!checkEmail(this.email),'email',"El formato del correo electrónico no es correcto");
		if(this.country=='ES') {
			var ci = !checkIdentificacion(this.ident,this.ident_type);
			var mi = '';
			switch(parseInt(this.ident_type)) {
				default:
				case 1: mi = 'El NIF no es correcto'; break;
				case 2: mi = 'El CIF no es correcto'; break;
				case 3: mi = 'El NIE no es correcto'; break;
				case 0: mi = 'Debes poner una identificación'; break;
			}
		}
		__Condition(ci,'ident',mi);
		__Condition(!checkPhone(this.phone,this.country),'phone',"Debes rellenar el número de teléfono (si el país es España, el número de teléfono debe tener al menos 9 dígitos, sino, se debe escribir en formato internacional (ej: +34.123456789).");
		if(this.fax.length>0) {
			__Condition(!checkPhone(this.fax,this.country),'fax',"El número de fax no es correcto. Debe contener al menos 9 dígitos.");
		}
		__Condition(this.country.length!=2,'country','Debes seleccionar un país');
		if(this.country=='ES') {
			__Condition(this.state=='','state','Debes seleccionar una provincia');
			__Condition(this.city=='','city','Debes seleccionar una localidad');
			var re = new RegExp('^'+this.state+'[0-9]{3}$','i');
			__Condition(!re.test(this.postal_code),'postal_code','El código postal es incorrecto con la província seleccionada');
		} else {
			__Condition(this.state.length<3,'state','Debes rellenar el estado');
			__Condition(this.city.length<3,'city','Debes rellenar la localidad');
			__Condition(this.postal_code<3,'postal_code','Debes rellenar el código postal');
		}
		__Condition(this.address.length<3,'address','Debes rellenar la dirección');
		var type = this.type;
		if(aOk.length>0) { $(aOk.join(this.type+', ')).filter(':first').DDFormErrorClean(); }
		if(aErrors.length) { $(aErrors.join(this.type+', ')).DDFormError(); }
		if(aMess.length>0) { alert( (title.length>0 ? title : '') + aMess.join("\n")); }
		return aErrors.length<=0;
	},
	this.fromXML = function(xml) {
		if(!xml) return this;
		this.isorg = $('isOrg',xml).text()=='true' || $('ident_type',xml).text()=='2';
		this.first_name = $('first_name',xml).text();
		this.last_name = $('last_name',xml).text();
		this.email = $('email',xml).text();
		this.email_repeat = this.email;
		this.phone = $('phone',xml).text();
		this.fax = $('fax',xml).text();
		this.org_name = $('org_name',xml).text();
		this.org_type = $('org_type',xml).text();
		this.ident_type = $('ident_type',xml).text();
		this.ident = $('ident',xml).text();
		this.address = $('address',xml).text();
		this.city = $('city',xml).text();
		this.state = $('state',xml).text();
		this.postal_code = $('postal_code',xml).text();
		this.country = $('country',xml).text();
		if(this.isCliente()) {
			this.user_name =  $('user_name',xml).text();
			this.password = $('password',xml).text();
			this.password_repeat = this.password;
			this.activo = $('activo',xml).text()=='true';
			this.facturable = $('facturable',xml).text();
			this.auto_renew_permited = $('autorenewpermited',xml).text();
			this.iva = $('iva',xml).text();
		} else if( this.isContacto() ) {
			this.__nic = '';
			if($('data', xml).length && $('data',xml).attr('nic')!='undefined') {
				this.__nic = $('data', xml).attr('nic');
			}
		}
		return this;
	};
	this.Copy = function(c) {
		if(this.isCliente()) {
			this.user_name = c.user_name;
			this.password = c.password;
			this.password_repeat = c.password_repeat;
			this.activo = c.activo;
			this.facturable = c.facturable;
			this.auto_renew_permited = c.auto_renew_permited;
			this.iva = c.iva;
		} else if(this.isContacto()) {
			this.__nic = c.__nic;
		}
		this.isorg = c.isorg;
		this.first_name = c.first_name;
		this.last_name = c.last_name;
		this.org_name = c.org_name;
		this.org_type = c.org_type;
		this.ident_type = c.ident_type;
		this.ident = c.ident;
		this.phone = c.phone;
		this.fax = c.fax;
		this.email = c.email;
		this.email_repeat = c.email_repeat;
		this.address = c.address;
		this.city = c.city;
		this.state = c.state;
		this.country = c.country;
		this.postal_code = c.postal_code;
		return this;
	};
	this.toArray = function() {
		var a = new Array();
		a['type'] = this.type;
		a['classtype'] = this.classtype;
		if(this.isCliente()) {
			a['user_name'] = this.user_name;
			a['password'] = this.password;
			a['password_repeat'] = this.password_repeat;
			if(this.check_password) { a['edit_password'] = 'true'; }
			if(this.activo) a['activo']='true';
			a['facturable']= this.facturable;
			a['auto_renew_permited'] = this.auto_renew_permited;
			a['iva'] = this.iva;
		} else if(this.isContacto()) {
			a['nic_handler_copy'] = this.__nic;
		}
		a['isorg'] = this.isorg ? 'true' : 'false';
		a['first_name'] = this.first_name;
		a['last_name'] = this.last_name;
		a['org_name'] = this.org_name;
		a['org_type'] = this.org_type;
		a['ident_type'] = this.ident_type;
		a['ident'] = this.ident;
		a['phone'] = this.phone;
		a['fax'] = this.fax;
		a['email'] = this.email;
		a['email_repeat'] = this.email_repeat;
		a['address'] = this.address;
		a['city'] = this.city;
		a['state'] = this.state;
		a['postal_code'] = this.postal_code;
		a['country'] = this.country;
		return a;
	};
	this.Serialize = function(add_type_arg) {
		var add_type = add_type_arg || false;
		var a = this.toArray();
		var str = '';
		for(var k in a) { str += '&' + encodeURIComponent(k + (add_type ? this.type : '')) + '=' + encodeURIComponent(a[k]); }
		return str;
	};
	this.Submit = function(params,f) {
		var func = f || function() {};
		if(this.Check(params)) {
			var str = this.Serialize();
			var url = params.url || '/api/clientes/modify/';
			$.ajax({url:url,dataType:'xml',data:str,success:function(xml) {
				var aErrores =  new Array();
				$('error',xml).each(function() { aErrores.push($(this).text()); });
				if(aErrores.length>0) { alert('Se han encontrado errores' + ": \n" + aErrores.join("\n")); }
				var aInforms = new Array();
				$('inform',xml).each(function() { aInforms.push($(this).text()); });
				if(aInforms.length>0) { alert(aInforms.join("\n")) }
				if(aErrores.length==0) { func(xml); }
			}});
		}
		return this;
	};
	this.fromTemplate = function() {
		this.isorg = this.__default_attr('#tipo_p_empresa','checked',false);
		this.first_name = this.__default_val('#first_name');
		this.last_name = this.__default_val('#last_name');
		this.email = this.__default_val('#email');
		this.email_repeat = this.__default_val('#email_repeat',this.email);
		this.phone = this.__default_val('#phone');
		this.fax = this.__default_val('#fax');
		this.org_name = this.__default_val('#org_name');
		this.org_type = this.__default_val('#org_type',1);
		this.ident_type = this.__default_val('#ident_type',1);
		this.ident = this.__default_val('#ident');
		// autocorrección del NIE
		this.ident = this.ident.replace(/[^A-Za-z0-9]/i,'');
		if(this.ident_type==3 && /^[a-z]\d{7}[a-z]$/i.test(this.ident)) {
			this.ident = this.ident.substr(0,1) + "0" + this.ident.substr(1,9);
		}
		this.__set_val('#ident',this.ident);
		this.address = this.__default_val('#address');
		this.state = this.__default_val('#state');
		this.city = this.__default_val('#city');
		this.postal_code = this.__default_val('#postal_code');
		this.country = this.__default_val('#country','ES');
		if(this.isCliente()) {
			this.user_name = this.__default_val('#user_name');
			this.password = this.__default_val('#password');
			this.password_repeat = this.__default_val('#password_repeat',this.password);
			this.check_password = this.__default_attr('#edit_password','checked',true);
			this.activo = this.__default_attr('#activo','checked',true);
			this.facturable = this.__default_val('#facturable',this.facturable);
			this.auto_renew_permited = this.__default_val('#autorenew',2);
			this.iva = this.__default_val('#ivaval',0.18);
		} else if(this.isContacto()) {
			this.__nic = this.__default_val('#nic_handler_copy');
		}
		return this;
	};
	this.toTemplate = function() {
		this.__set_attr('#tipo_p_empresa','checked',this.isorg?'checked':'');
		this.__set_attr('#tipo_p_particular','checked',!this.isorg?'checked':'');
		this.__set_val('#first_name',this.first_name);
		this.__set_val('#last_name',this.last_name);
		this.__set_val('#org_name',this.org_name);
		this.__set_val('#org_type',this.org_type);
		this.__set_val('#email',this.email);
		this.__set_val('#email',this.email_repeat);
		this.__set_val('#phone',this.phone);
		this.__set_val('#ident_type',this.ident_type);
		this.__set_val('#ident',this.ident);
		this.__set_val('#fax',this.fax);
		this.__set_val('#postal_code',this.postal_code);
		this.__set_val('#address',this.address);
		this.__set_val('#country',this.country);
		this.ChangePropietario();
		this.__update_div_address();
		if(this.isCliente()) {
			this.__set_val('#user_name',this.user_name);
			this.__set_val('#password',this.password);
			this.__set_val('#password_repeat',this.password_repeat);
			this.__set_attr('#activo','checked',this.activo?'checked':'');
			this.__set_val('#facturable',this.facturable);
			this.__set_val('#autorenew',this.auto_renew_permited);
			this.__set_val('#ivaval',this.iva);
		} else if (this.isContacto()) {
			this.__set_val('#nic_handler_copy', this.__nic);
		}
		return this;
	}
	this.getTemplate = function(div,f) {
		var myself = this;
		var func = f || function() {};
		$.ajax({url:'/api/clientes/gettemplate/',data:{ type:this.type,classtype:this.classtype},
				success:function(data) { $(div).html(data); func(data,myself); }});
		return this;
	};
	this.ChangePropietario = function() {
		var frmType = ($('#tipo_p_empresa'+this.type).attr('checked') ? '#tipo_p_empresa' : '#tipo_p_particular') + this.type;
		if($(frmType).val() == 'empresa') {
			$('#org_name'+this.type).parent().show();
			$('#org_type'+this.type).parent().show();
			this.ident_type = this.country=='ES' ? 2 : 0;
		} else {
			$('#org_name'+this.type).val('').parent().hide();
			$('#org_type'+this.type).val(1).parent().hide();
			if(this.ident_type!=3) {
				this.ident_type = this.country=='ES' ? 1 : 0;
			}
		}
		this.__set_val('#ident_type',this.ident_type);
		return this;
	};
	this.__update_div_address = function(state_focus) {
		var myself = this;
		var sf = state_focus || false;
		$.ajax({ url: '/api/clientes/getcountrytemplate/', data: { country: this.country, state: this.state, city: this.city, type: this.type },
				success: function(data) {
					$('#countryselected'+myself.type).html(data);
					if(!sf){$('#state'+myself.type).focus();}else{$('#city'+myself).focus();}
					myself.fromTemplate();
					myself.ChangePropietario();
				}
		});
		return this;
	}
	this.ChangePais = function() {
		this.country = $('#country'+this.type).val(); this.state = ''; this.city = '';
		return this.__update_div_address();
	};
	this.ChangeState = function() {
		this.country = $('#country'+this.type).val(); this.state = $('#state'+this.type).val(); this.city = '';
		return this.__update_div_address(true);
	};
	this.ChangeCity = function() {
		this.city = $('#city'+this.type).val();
		var myself = this;
		$.ajax({url:'/info/postalcode/',data:{id:this.city},dataType:'xml',
				success:function(xml) { $('#postal_code'+myself.type).val($('postal_code',xml).text()).focus();}});
		return this;
	};
	this.GenerateContrasena = function() {
		generate_password(8,'password'+this.type,'password_repeat'+this.type,'password_generate'+this.type);
		return this;
	};
	return this;
};

/*============================================================
  Mis contactos
============================================================*/
function MisCont_InsertAfterRow(elem,key,url,data) {
	var p = $(elem).parents('tr:first');
	if(!$(p).next().is('.__insert_before_row__')) {
		$('<tr><td colspan="' + $(p).children('td').length + '"></td></tr>').addClass('__insert_before_row__').addClass('orange').insertAfter(p);
	}
	var div = $(p).next().children('td');
	var key_div = '__insert_tr_' + key;
	if(!(div.children('div.' +key_div).length) ) {
		div.append( $('<div><span class="c_gris f_small">Cargando...</span></div>').hide().
				addClass(key_div).MaxHeight({h:'300px'}).addClass('cuadronota').css({margin:'0 auto', width:'90%'}) );
		$.ajax({
			url: url,
			data: data,
			success: function(html) {
				var aux = div.children('div.' + key_div);
				aux.children().not('img').remove();
				aux.html(html);
			}
		});
	}
	div.children('div:visible').not('div.'+key_div).hide();
	div.children('div.' +key_div).toggle();
	if(div.children('div:visible').length>0) {
		div.parent().show().prev().removeClass('orange');
	} else {
		div.parent().hide().prev().addClass('orange');
	}
}
function ViewContactInfo(elem,nick) {
	MisCont_InsertAfterRow(elem,'viewcot','/info/infocontact/', { format: 'html', nick: nick});
}
function VerDominiosNick(elem,nick)
{
	MisCont_InsertAfterRow(elem,'viewdom','/info/infocontactdomain/', { format: 'html', nick: nick});
}
function EliminarContacto(nick,a)
{
	var action = a || '/admin/miscontactos/';
	if(confirm('¿Estás seguro de eliminar el contacto '+nick+'?')) {
		$('<form method="POST" name="__form_eliminar_nick" action="' + action  +
			'" ><input type="hidden" name="eliminar" value="'+nick+'" /></form>').appendTo('body').submit().remove();
	}
}

/*============================================================
  Plugin de busqueda
============================================================*/

var SearchPlugin = {
	id: 'search_plugin_popup',
	obj: null,
	created: false,
	delay_show: 1000,
	delay_show_efect: 'slow',
	delay_close_effect: 'slow',
	delay_close: 10000,
	create: function() {
		if(isBrowserIE(7)) return false;
		if(this.evalCookie()) return false;
		if(this.created) return true;
		$('#header').css('position','relative');
		this.obj = $('<a id="'+this.id+'" onclick="installSearchEngine();return false;" href="#" '+
				' title="Instala el plugin de búsqueda de dominios de DonDominio.com" ></a>');
		this.obj.css({height:0,width:0,display:'none'}).appendTo('#header');
		this.created = true;
		var myself = this;
		STO(function() { myself.show(); },this.delay_show); 
		return true;
	},
	show: function() {
		if(!this.created) return;
		var myself = this.setCookie();
		this.obj.animate({ height : "116px", width: "300px" }, this.delay_close_effect,'linear',
				function() { STO(function() { myself.close(); },myself.delay_close); });
	},
	close: function() {
		this.obj.fadeOut(this.delay_close_effect);
	},
	evalCookie: function() {
		return $.cookie(this.id)=='1';
	},
	setCookie: function(days) {
		$.cookie(this.id,'1',{expires: 1, path: '/'});
		return this;
	}
};

(function($) {
	/*********************
	Pestañas
  	*********************/
 	$.fn.DDPestanyas = function(o) {
		o = $.extend({
				effect_div: 'normal',
				active: 0,
				auto_select: true
			}, o || {});
		return $(this).each(function() {
			var titol = $('div.pest_wrapper_right #div_pestanyes div.pest_titol',this);
			var others = $('div.pest_wrapper_right #div_pestanyes > div',this).not('div.pest_titol');
			var __a_link_pestanyes = function (e,effects) {
				$(e).parents('ul:first').find('a.selected').removeClass('selected');
				$(e).addClass('selected');
				titol.html($(e).html())
				others.stop().filter(':visible').hide();
				var key = /#([a-z0-9\_]+)$/.exec($(e).attr('href'));
				effects ?  $("#pest_" + key[1]).slideDown(o.effect_div) : $("#pest_" + key[1]).show();
			}
			var ul = $('ul.pestanyes li a',this).removeClass('selected').click(function() {
				__a_link_pestanyes(this,false);
				return false;
			});
			var __a_link_pestanyes_sel = function(sel,effects) {
				__a_link_pestanyes(typeof(sel)=='string' ? ul.filter('[href$="#' + sel + '"]') : ul.eq(sel), effects);
			}
			if(o.auto_select) {
				var re = new RegExp('^(.*?)#([a-z0-9\_]+)$','i');
				if(re.test(document.location.href)) {
					var m = re.exec(document.location.href);
					__a_link_pestanyes_sel(m[2],false);
					o.active = -1;
				}
			}
			if(o.active>=0) {
				__a_link_pestanyes_sel(o.active,false);
			}
		});
	};
	/*********************
	 Pestanyas horizontal
	**********************/
 	$.fn.DDPestanyasBuscar = function(o) {
		o = $.extend({
				selected: null,
				callback: null,
				klass_selected: 'catselected'
				}, o || {});
		return $(this).each(function() {
			$(this).children('a').click(function() {
				var cat = '#' + GetAnchor( this );
				$(this).parent().children('.'+o.klass_selected).removeClass(o.klass_selected);
				$(this).addClass(o.klass_selected);
				$(cat).parent().children('div:visible').not('.noshadow').not(cat).hide();;
				$(cat + ':hidden').show();
				if( $.isFunction( o.callback) ) {
					o.callback( this );
				}
				return false;
			});
			if(typeof(o.selected)=='number') {
				$(this).children('a:eq('+o.selected+')').click();
			} else if(typeof(o.selected)=='string') {
				$(this).children('a[href$="' + o.selected + '"]').click();
			}
		});
	};
	/*********************
  	Plugin acordeon y carrusel
  	*********************/
 	$.fn.Accordion = function(o) {
		o = $.extend({
				selected: 0,
				desp: {},
				pleg:{},
				speed: 'fast',
				fx: 'linear',
				class_temp: '__accordion_pleg',
				callback: function(){},
				calllast: function(){}
				},o || {});
		var myself = $(this);
		var AccordionSeleccionar = function() {
			$(this).removeClass(o.class_temp).animate(o.desp,o.speed,o.fx,o.callback);
		};
		var AccordionDeSeleccionar = function() {
			$(this).addClass(o.class_temp).css(o.pleg).each(o.calllast);
		};
		$(this).not(':eq('+o.selected+')').each(AccordionDeSeleccionar);
		$(this).eq(o.selected).each(AccordionSeleccionar);
		return $(this).click(function() {
			$(this).dequeue();
			if($(this).hasClass(o.class_temp)) {
				myself.not('.'+o.class_temp).each(AccordionDeSeleccionar);
				$(this).each(AccordionSeleccionar);
			}
		});
	};
 	$.fn.Carrusel = function(o) {
		o = $.extend({
				speed: 'slow',
				type: 'a',
				time: 3000, // 1 seg transition
				callback: function(){},
				css_temp: '__carrusel_temp__',
				fx: 'linear'
			}, o || {});
		var sons = $(this).children();
		for(var i=0;i<sons.length;i++) {
			sons.eq(i).addClass(o.css_temp + i);
		}
		var first_son = sons.eq(0);
		var aEffects = [
			[
				{ marginLeft: '-' + parseInt(first_son.width()) + 'px'},
				{ marginLeft: parseInt(first_son.css('marginLeft')) + 'px'},
				{ width: $(sons).length * parseInt(first_son.width()), height: $(this).height() }
			],[
				{ marginTop: '-' + parseInt(first_son.height()) + 'px'},
				{ marginTop: parseInt(first_son.css('marginTop')) + 'px'},
				{ height: $(sons).length * parseInt(first_son.height()), width: $(this).width() }
			]];
		var myself = $(this);
		this.__Carrusel = function() {
			var __c = 0;
			switch(o.type) {
				case 'v': __c = 1; break;
				case 'a': __c = Math.round(Math.random() * 10) % 2; break;
				default: case 'h': __c = 0; break; 
			};
			$(myself).css(aEffects[__c][2]).children(':first').animate( aEffects[__c][0], o.speed, o.fx, function() {
					$(myself).append($(this));
					$(this).css(aEffects[__c][1]);
					var jSel = $(myself).children(':first');
					var sons = $(myself).children();
					var selected = 0;
					for(var i=0;i<sons.length;i++) {
						if(jSel.hasClass(o.css_temp+i)) {
							o.callback(jSel,i);
							break;
						}
					}
			});
		};
		this.CarruselSTO = null;
		this.CarruselStart = function() {
			this.CarruselSTO = setInterval(this.__Carrusel,o.time);
			return this;
		};
		this.CarruselStop = function() {
			if(this.CarruselSTO!=null) {
				clearTimeout(this.CarruselSTO);
				this.CarruselSTO = null;
			}
			return this;
		};
		this.CarruselSelected = function(selected) {
			this.CarruselStop();
			var sons = $(myself).children();
			var jSel = null;
			for(var i=0;i<sons.length;i++) {
				if(sons.eq(i).hasClass(o.css_temp+selected)) {
					break;
				} else {
					$(myself).append(sons.eq(i));
				}
			}
			var jSel = $(myself).children('.'+o.css_temp+selected);
			$(myself).prepend(jSel);
			o.callback(jSel,selected);
			this.CarruselStart();
			return this;
		};
		return this;
	};
	$.fn.Link2Post = function(o) {
		o = $.extend({
			}, o || {});
		return $(this).unbind('click').click(function() {
			var href = $(this).attr('href');
			var external = $(this).attr('rel') == 'external';
			var query_string = href.replace(/^([^\?]+)\?/,'');
			var action = href.replace(/\?.*$/,'');
			if(query_string.length>0) {
				var myform = $('<form method="POST" name="__link2postform__" id="__link2postform__" action="' + action + '" ' +
					(external?' target="_blank" ':'') + ' ></form>').appendTo('body');
				var aux = query_string.split('&');
				for(var i in aux) {
					var var_name 	= aux[i].replace(/\=.*$/,'');
					var var_value	= aux[i].replace(/^([^\=]+)\=/,'');
					$('<input type="hidden" name="'+var_name+'" value="'+ var_value+ '" />').appendTo(myform);
				}
				$(myform).submit().remove();
			} else {
				if(external) window.open(href);
				else document.location.href = href;
			}
			return false;
		});
	};
	/*******************************************
	  Tooltip
	***********************************************/
	$.ToolTip = function(o) {
		o = $.extend({ }, o || {});
		if($('body .tooltip:first').length) {
			this.obj = $('body .tooltip:first');
		} else {
			this.obj = $('<div class="tooltip"><div class="tooltip-content"></div><div class="tooltip-footer"></div>').hide();
			$(this.obj).bind('mouseleave',function() { $(this).hide(); });
			$(this.obj).appendTo('body');
		}
		this.Position = function(x,y) { this.obj.css({position: 'absolute', left: x, top: y}); return this; };
		this.CapturePosition = function(e) { var pos = CaptureMousePosition(e); return this.Position(pos[0],pos[1]); };
		this.Show = function() { isBrowserIE() ? $(this.obj).show() : $(this.obj).fadeIn('normal'); return this; };
		this.Hide = function() { isBrowserIE() ? $(this.obj).hide() : $(this.obj).hide('fast'); return this; };
		this.Cargando = function(text) {
			var t = text || '<span class="f_small"><img src="/images/buscando.gif" alt="" style="vertical-align:middle" ></span>';
			return this.Content(t).Show();
		};
		this.Content = function(html,title) {
			var t = '';
			if(title) {
				t += '<h4>' + title + '</h4>';
			}
			t += html;
			$(this.obj).find('.tooltip-content').html(t);
			return this;
		};
		return this;
	};
	/*******************************************
	  Max Height de un elemento
	***********************************************/
	$.fn.MaxHeight = function(o) {
		o = $.extend({ h: '250px', overflow: 'auto'}, o || {} );
		var __mh_data = {};
		__mh_data.overflow = o.overflow;
		if(isBrowserIE(7)) {
			__mh_data.height = o.h;
		} else {
			__mh_data.maxHeight = o.h;
		}
		return $(this).css(__mh_data);
	};
	/*******************************************
 		 minimizar y ocultar
	***********************************************/
 	$.fn.MiniSettings = function(o) {
		o = $.extend({
				cookie_settings: { expires: 1000 }, // poner "path: '/'", para que la cookie sea absoluta
				cookie_name: 'ddset',
				visible: true
			}, o || {});
		return $(this).each(function() {
			$(this).wrap('<div />');
			var wrapper = $(this).parent().addClass('a_filtro_div');
			$('<a href="#" title="Ver/Mostrar filtros de búsqueda">Ocultar</a>').
				click( function() {
					var oculto = $(this).hasClass('oculto');
					oculto = !oculto;
					$.cookie( o.cookie_name , oculto ? '0' : '1', o.cookie_settings);
					var fs = $(this).parents('div.a_filtro_div').children().not('.a_filtro');
					if(!oculto) {
						$(this).addClass('mostrar').removeClass('oculto').html("Ocultar");
						fs.removeClass('oculto');
					} else {
						$(this).removeClass('mostrar').addClass('oculto').html("Mostrar");
						fs.addClass('oculto');
					}
					return false;
				}).
				addClass('mostrar a_filtro').
				prependTo( wrapper);
			var cookie_val = $.cookie(o.cookie_name);
			if(cookie_val!=null || !o.visible) {
				if(cookie_val=='0' || !o.visible) {
					$('a.a_filtro', wrapper).addClass('oculto').html("Mostrar");
					$(this).addClass('oculto');
				}
			}
		});
	};
	/*============================================================
	 * Tipo de plantillas
	 * ===========================================================*/
	$.fn.Template = function(o) {
		o = $.extend({ data: {}, elem: '#content', url: null, post: false, viewloading: true, exec: false}, o || {});
		if(typeof(o.data)=='string') {
			o.data += '&__tpl=1';
		} else {
			o.data.__tpl = 1;
		}
		return $(this).addClass('__template').each(function() {
				var url = o.url;
				var postmethod = o.post;
				if( url == null ) {
					if($(this).is('a')) {
						url = $(this).attr('href');
					} else if( $(this).is('form') ) {
						url = $(this).attr('action');
						if( $(this).attr('method')=='post') {
							postmethod = true;
						}
					}
					url = url.replace(/\#.*$/,'');
				}
				if(!o.exec) {
					$(this).click(function() {
						if(typeof(o.viewloading)=='boolean') {
							if(o.viewloading) {
								$(o.elem).DDLoading('block');
							}
						} else {
							$(o.viewloading).DDLoading('block');
						}
						if(postmethod) {
							$.post(url, o.data, function(html) {
								$(o.elem).html(html);
								$.TemplateInit();
							});
						} else {
							$.get(url, o.data, function(html) {
								$(o.elem).html(html); 
								$.TemplateInit();
							});
						}
						return false;
					});
					if($(this).is('form')) {
						$(this).click();
					}
				} else {
					if(typeof(o.viewloading)=='boolean') {
						if(o.viewloading) {
							$(o.elem).DDLoading('block');
						}
					} else {
						$(o.viewloading).DDLoading('block');
					}
					if(postmethod) {
						$.post(url, o.data, function(html) {
							$(o.elem).html(html);
							$.TemplateInit();
						});
					} else {
						$.get(url, o.data, function(html) {
							$(o.elem).html(html); 
							$.TemplateInit();
						});
					}
				}
		});
	};
	$.fn.TemplateBadge= function(o) {
		o = $.extend({}, o || {});
		return $(this).each(function() {
			var l = (parseInt($('a.badge', this).width()) + 15) + "px";
			$(this).
				width(l).
				bind('mouseenter', function() {
					$(this).css('width', '60px').children('.badgenotif').show();
				}).
				bind('mouseleave', function() {
					var l = (parseInt($('a.badge', this).width()) + 15) + "px";
					$(this).css('width', l).children('.badgenotif').hide();
				});
		});
	}
	$.TemplateInit = function(o) {
		$('#content').DDLoading('remove');
		$('#content_header ul.menusimg li a').Template();
		$('#content_header ul.menusimg li .badgewrapper').TemplateBadge();
	};
	/*******************
	 * Cache info prod
	 * *****************/
	$.fn.CacheInfoProd = function(key) {
		var offset = $(this).offset();
		$.ToolTip().Position(offset.left,offset.top).Cargando();
		if(DDCacheInfoProd[key]) {
			$.ToolTip().Content(DDCacheInfoProd[key]);
		} else {
			$.ajax({
				url: '/info/infoprodext/',
				data: {format: 'html', key: key },
				success: function(data) {
					DDCacheInfoProd[key] = data;
					$.ToolTip().Content(DDCacheInfoProd[key]);
				}
			});
		}
	};
	/*******************
	 * Cargando...
	 * *****************/
	$.fn.DDLoading = function( mode, o ) {
		o = $.extend({
					text: 'Cargando datos...'
				}, o || {});
		return $(this).each(function() {
			switch(mode) {
				case 'block':
					var myself = $(this).addClass('ajaxloadingwrapper').css('min-height','75px');
					var pos = { top: 0, left: 0}
					var p = $(this).position();
					pos.top += parseInt( p.top);
					pos.left += parseInt( p.left );
					var w = parseInt( $(this).width() );
					var div = $('<div><img alt="" src="/images/cargando5.gif" />' + o.text + '</div>').
						addClass('ajaxloading').
						css( { width: w + 'px', top: pos.top + 'px', left: pos.left + 'px' });
					if( parseInt($(this).height())<=70) {
						div.css('margin-top', 0);
					}
					myself.after( div );
					break;
				case 'table':
					var myself = $(this);
					var table = $('table', myself).addClass('ajaxloading');
					var pos = { top: 0, left: 0};
					if(table.css('position')=='relative') {
						var p = table.position();
						pos.top += parseInt(p.top);
						pos.left += parseInt(p.left);
					}
					$('table tbody', myself).each(function() {
						var p = $(this).position();
						pos.top += parseInt(p.top);
						pos.left += parseInt(p.left);
						var w = parseInt( $(this).width() );
						var div = $('<div><img alt="" src="/images/cargando5.gif" />' + o.text + '</div>').
							addClass('ajaxloading').
							css( { width: w + 'px', top: pos.top + 'px', left: pos.left + 'px' });
						if( parseInt($(this).height())<=70) {
							div.css('margin-top', 0);
						}
						myself.append( div );
					});
					break;
				case 'linkinlinemini':
					$(this).after('<span class="ajaxloading">' + '</span>');
					$(this).addClass('ajaxloadingwrapper ajaxloadingshow').hide();
					break;
				case 'linkinline':
					$(this).after('<span class="ajaxloading">' + o.text + '</span>');
					$(this).addClass('ajaxloadingwrapper ajaxloadingshow').hide();
					break;
				case 'inline':
					$(this).append( '<span class="ajaxloading">' + o.text + '</span>' );
					break;
				case 'center':
					$(this).append( '<p class="ajaxloading"><span>' + o.text + '</span></p>');
					break;
				case 'centeradd':
					$(this).addClass('ajaxloadingwrapper').after( $('<p class="ajaxloading"><span>' + o.text + '</span>') );
					break;
				case 'centerbefore':
					$(this).addClass('ajaxloadingwrapper').before( $('<p class="ajaxloading"><span>' + o.text + '</span>') );
					break;
				case 'delete':
				case 'remove':
					if($(this).is('.ajaxloadingwrapper')) {
						$(this).next('.ajaxloading').remove();
						$(this).prev('.ajaxloading').remove();
					}
					if($(this).is('.ajaxloadingshow')) {
						$(this).removeClass('ajaxloadingshow').show();
					}
					$(this).removeClass('ajaxloading').removeClass('ajaxloadingwrapper');
					$('table.ajaxloading',this).removeClass('ajaxloading');
					$('.ajaxloading', this).remove();
					break;
			}
		});
	};
	/*******************
	 * Formularios/table/paginacion
	 * *****************/
	$.fn.DDFormFocused = function( o ) {
		o = $.extend( { text: '', onblur: false, assign: false }, o || {} );
		return $(this).each( function() {
			if(o.assign) {
				if( !$(this).val().length ) {
					$(this).val( o.text );
				}
			}
			if(!$(this).val().length) {
				$(this).val( o .text );
			}
			$(this).focus( function() {
				if( $(this).val() == o.text) {
					$(this).val('');
				}
			});
			if(o.onblur) {
				$(this).blur( function() {
					if( $.trim( $(this).val() ) == '' ) {
						$(this).val( o.text );
					}
				});
			}
		});
	}
	$.fn.DDFormErrorClean = function( o ) {
		o = $.extend( { klass: 'formularierror', all: true}, o || {} );
		return $(this).each(function() {
			if(o.all) {
				var f = $(this).is('form') ? $(this) : $(this).parents('form:first');
				f.find('.' + o.klass).removeClass(o.klass);
			} else {
				$(this).parent().removeClass(o.klass);
			}
		});
	};
	$.fn.DDFormError = function( o ) {
		o = $.extend( { klass: 'formularierror' }, o || {} );
		return $(this).each(function() {
			$(this).parent().addClass( o.klass );
		});
	};
	$.fn.DDFormGraph = function( toDiv, aTypes, aView ) {
		return $(this).each(function() {
			var urls = $(this).attr('action');
			urls = urls + (urls.indexOf('?')==-1 ? '?':'')+'&'+ $(this).serialize() + '&export=graph&nocache=' + (new Date()).getTime();
			var div = $(toDiv, this);
			if(div.length && aTypes.length) {
				div.empty();
				if(!aView) {
					$('<a href="#" class="btnadmin" title="Ver gráficos">Ver gráficos</a>').click(function() {
						var p = $(this).parent();
						p.children('.ddgraphimg').each(function() {
							$(this).attr('src', $(this).attr('_src')).css('display','block');
						});
						p.children().not('.ddgraphimg').remove();
						return false;
					}).appendTo(div);
				}
				for(var k in aTypes) {
					var t= /^\d+$/.test(k) ? "Gráfico" : k;
					var src = urls + '&graphtype=' + aTypes[k];
					var co = { background: 'url(/images/buscando3.gif) no-repeat center center', margin: '20px auto', display: aView?'block':'none', color: 'lightgrey' };
					$('<img class="ddgraphimg" alt="'+t+'" title="'+t+'" src="' + (aView?src:'') + '" ' + (aView?'':' _src="'+src+'"') + ' />').css(co).appendTo(div);
				}
			}
		});
	};
	$.fn.DDForm = function(o) {
		o = $.extend({
				filters: {
					page: 'page_filter',
					order: 'order_filter',
					order_type: 'order_type_filter',
					input_export: 'export',
					limit: 'limit_filter'
				},
				reprocess: true,
				preempty: false,
				faceboxmode: false,
				ajaxfilter: '&is_ajax_filter=is_ajax',
				content: '.ddform_cnt',
				graph_content: '.ddform_cnt_graph',
				autoview_graph: false,
				fieldset: 'fieldset.filtro',
				filtrar: 'input.ddform_fil',
				todos: 'input.ddform_filall',
				headers: {},
				graphs: []
			}, o || {});
		return $(this).each(function() {

			$(o.content + ' table thead tr th a', this).remove();
			$(o.fieldset + ' select[onchange]', this).unbind('change').removeAttr('onchange', '');
			$(o.fieldset + ' input[onclick]', this).unbind('click').removeAttr('onclick', '');
			$(o.content + ' table tfoot td.paginacion a[onclick]').unbind('click').removeAttr('onclick');
			$(o.content + ' table tfoot div.__export_link__ a[onclick]').unbind('click').removeAttr('onclick');

			$('input:text', $(o.fieldset, this)).unbind('change').change(function() {
				var f = $(this).parents('form');
				f.find('input[name="' + o.filters.page + '"]').val(0);
			});
			$('select', $(o.fieldset, this)).unbind('change').change(function() {
				var f = $(this).parents('form');
				f.find('input[name="' + o.filters.page + '"]').val(0);
				f.submit();
			});
			$(o.fieldset + ' ' + o.filtrar, this).unbind('click').click(function() {
				var f = $(this).parents('form');
				f.find('input[name="' + o.filters.page + '"]').val(0);
				f.submit();
				return false;
			});
			$(o.fieldset + ' ' + o.todos, this).unbind('click').click(function() {
				var f = $(this).parents('form');
				f.find('input[name="' + o.filters.page + '"]').val(0);
				f.find('input:text').val('');
				f.find('select').not( '[name="' + o.filters.limit + '"]' ).each(function() {
					$('option:selected', this).attr('selected', false);
					$('option:first',this).attr('selected', true);
				});
				f.submit();
				return false;
			});
			for(var key in o.headers) {
				var order = o.headers[key];
				var td = $(o.content + ' table thead tr th:eq(' + key + ')');
				$('<a href="#'+order+'" title="Ordenar ascendente"><img src="/images/flecha_arriba.gif" alt="" /></a>').
					click(function() {
						var om = $(this).attr('href').replace(/^.*#/,'');
						$(this).parents('form').find('input[name="' + o.filters.page + '"]').val(0);
						$(this).parents('form').find('input[name="' + o.filters.order + '"]').val(om);
						$(this).parents('form').find('input[name="' + o.filters.order_type+ '"]').val('ASC');
						$(this).parents('form').submit();
						return false;
					}).prependTo( td );
				$('<a href="#'+order+'" title="Ordenar descendente"><img src="/images/flecha_abajo.gif" alt="" /></a>').
					click(function() {
						var om = $(this).attr('href').replace(/^.*#/,'');
						$(this).parents('form').find('input[name="' + o.filters.page + '"]').val(0);
						$(this).parents('form').find('input[name="' + o.filters.order + '"]').val(om);
						$(this).parents('form').find('input[name="' + o.filters.order_type+ '"]').val('DESC');
						$(this).parents('form').submit();
						return false;
					}).appendTo( td );
			}
			$(o.content + ' table tfoot td.paginacion a').click(function() {
				var page = $(this).attr('href').replace(/^.*#/,'');
				$(this).parents('form').find('input[name="' + o.filters.page + '"]').val( page );
				$(this).parents('form').submit();
				$(this).parents('td').empty().DDLoading('inline');
				return false;
			});
			$(o.content + ' table tfoot div.__export_link__ a').click(function() {
				var method = $(this).attr('href').replace(/^.*#/,'');
				var f = $(this).parents('form');
				var input = $('<input type="hidden" name="' + o.filters.input_export + '" value="' + method + '" />' ).appendTo( f );
				f.submit();
				input.remove();
				return false;
			});
			if(o.graphs.length) {
				$(this).DDFormGraph( o.graph_content, o.graphs, o.autoview_graph);
			}
			$(this).unbind('submit').submit(function() {
				var cnt = $(o.content, this);
				var myOpts = o;
				var export_method = $(this).children('input[name="' + o.filters.input_export + '"]').length;
				var urls = $(this).attr('action');
				var datas = $(this).serialize();
				SaveSearchData(datas);
				if(o.faceboxmode) {
					$.facebox.View(urls + (urls.indexOf('?')==-1 ? '?':'')+'&'+datas); 
				} else if(cnt.length && !export_method) {
					if( $('table',cnt).length ) {
						cnt.DDLoading( 'table' );
					} else if( $('.nofound', cnt).length ) {
						$('.nofound',cnt).DDLoading('centeradd').remove();
					}
					// Efects
					//cnt.css('opacity',0.8);
					$.ajax({
						url: urls,
						data: datas + o.ajaxfilter,
						type: 'POST',
						error: function() {
							cnt.DDLoading('remove').html('<div class="error_messages"><p>Error de conexión</p></div>');
						},
						success: function(html) {
							// Reset Effects
							//	$(cnt).css('opacity',1);
							if(myOpts.preempty) {
								cnt.empty().html( html ) ;
							} else {
								cnt.html( html );
							}
							if(myOpts.reprocess) {
								$('a.__link2post__', cnt).Link2Post();
								$('a[rel="external"]',cnt).not('.__link2post__').click(function() {
									window.open($(this).attr('href'));
									return false;
								});
								cnt.parents('form').DDForm( myOpts );
							}
						}
					});
					return false;
				}
				return true;
			});
		});
	};

})(jQuery);

/****************
  Eventos al inicializar
  **************/
$(function() {
		$('#content_header ul.menusimg li .badgewrapper').TemplateBadge();
		$('#main_registrar_form input[name="domain"]').DDFormFocused({ text: "tudominio" });
		$('#main_registrar_form').submit(function() {
			var input = $('input[name="domain"]',this);
			if(check_domain_format(input)) {
				//redirect($(this).attr('action') + input.val() + '/');
				input.addClass('loading');
				$.ajax({
					url: $(this).attr('action'),
					data: { domain: input.val(), __tpl: true},
					success: function(html) {
						input.removeClass('loading');
						$('#content').html(html);
					}
				});
			}
			return false;
		});
		cestacompra.create();
		setInterval(function() {
				var a = $('div#shopping_cart a:first');
				var num = parseInt(a.text());
				if(num>0) {
					if(a.is('.conproductos')) {
						a.removeClass('conproductos');
					} else {
						a.addClass('conproductos');
					}
				} else {
					a.removeClass('conproductos');
				}
		},750);
		$('fieldset.filtro').not('.nomini').MiniSettings();
		$('a[rel="external"], a.ayuda, a.ayudamini').click(function() {
			window.open($(this).attr('href'));
			return false;
		});
		$('a.__link2post__').Link2Post();
      $('#fast_search_domain').
			DDFormFocused({text: "Búsqueda rápida", onblur: true, assign: true}).
			keypress(function(e) {
				if(e.which==13 && $(this).val().length>1) {
					redirect('/info/completedominios/?format=html&match=' + $(this).val());
				}
			}).
			autocomplete('/info/completedominios/',{
				resultsClass: 'ac_results fast_search_domains',
				delay: 400,
				minChars: 2,
				cacheLength: 10,
				extraParams: { limit: 30, format: 'html' },
				width: 250,
				onFindValue: 	function(li) { if(li!=null && li.selectValue.length>0) { redirect('/info/completedominios/?format=html&match=' + li.selectValue); }},
				onItemSelect:	function(li) { if(li!=null && li.selectValue.length>0) { redirect('/info/completedominios/?format=html&match=' + li.selectValue); }},
				formatItem:		function(row) { return '<span style="font-weight:bold">' + row[0] + '</span>'; }
			});
		SearchPlugin.create();
		$('div.rhi .inputcontainer input').change( function() {
			if(!$(this).is(':checked')) { $(this).parent().removeClass('selected'); } else { $(this).parent().addClass('selected'); }
		});
		$.facebox.Init();
});
