if(!window.$JTA) {
  var $JTA = [];
  var $JTLT = { };
  var $JTL = window.JSTC_Translate || function(t) { return $JTLT[t] || t; }
}

if(!window.JSKitLib) JSKitLib = {};

JSKitLib.getOuterHTML = function(node) {
    var clone = node.cloneNode(true);
    var parent = document.createElement('div');
    parent.appendChild(clone);
    var ihtml = parent.innerHTML;

    // ff converts sp characters inside of href to hex ascii
    var ihtmlHref = ihtml.match(/href\s*=\s*"[^"]*(%7B|%7D)[^"]*"/g) || [];
    for (var i=0; i< ihtmlHref.length; i++) {
      var a = ihtmlHref[i];
      var b = a.replace(/%7B/, '{');
      b = b.replace(/%7D/, '}');
      ihtml = ihtml.replace(a, b);
    }
    return ihtml;
};

JSKitLib.pngBar = function(color, div, fixed) {
	var str;
	var url = "'//js-kit.com/images/bars/bar-" + color + ".png'";
	if(document.body.filters) {
		str = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src="
			+ url + ", sizingMethod='"+(fixed?'crop':'scale')+"')";
		if(div) div.runtimeStyle.filter = str;
		return "filter: " + str + ";";
	} else {
		str = "url(" + url + ")";
		if(div) div.style.backgroundImage = str;
		return "background: " + str + ";";
	}
  };

JSKitLib.addPNG = function(node, imageURL) {
	if (JSKitLib.isPreIE7()) {
		node.runtimeStyle.filter
			= "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
			+ imageURL + "', sizingMethod='crop')"
	} else {
		node.style.backgroundImage = 'url(' + imageURL + ')';
		node.style.backgroundRepeat = 'no-repeat';        
	}
	return node;
}

JSKitLib.map = function(f, arr) {
	if(arr) for(var i = 0; i < arr.length; i++) f(arr[i], i, arr);
}
JSKitLib.filter = function(f, arr) {
	var newArr = [];
	if(arr)
		for(var i = 0; i < arr.length; i++)
			if(f(arr[i], i, arr))
				newArr.push(arr[i]);
	return newArr;
}

JSKitLib.isPreIE7 = function() {
	if (document.body.filters && parseInt(navigator.appVersion.split("MSIE")[1]) < 7)
		return true;
}
JSKitLib.createMiniStarObject = function(rating, scale, specs) {

	var fullStar = specs.full;
	var emptyStar = specs.empty;
	var starWidth = specs.width + 'px';
	var starHeight = specs.height + 'px';
    
	var setImage = function(star, imageURL) {
		if(star.imageURL == imageURL)
			return; // Already set and we know it

		star.imageURL = imageURL;
		JSKitLib.addPNG(star, imageURL);
	}

	var obj = document.createElement('div');

	/* Increment by Full Star Ratings */
	for (var i=2; i <= scale; i += 2) {

		var star = document.createElement('div');

		star.style.cssFloat   = 'left';
		star.style.styleFloat = 'left';
		star.style.width    = starWidth;
		star.style.height   = starHeight;
		star.style.fontSize = starHeight; // ie6

		if (rating >= i) {
			setImage(star, fullStar);
		} else {
			setImage(star, emptyStar);
		}

		obj.appendChild(star);
	}

	return obj;
}

new JSTC();	/* JavaScript Top Class */

function JSTC() {
	/* Find the target DIV for all the blog comments */
	this.jpaIndex = $JTA.length;
	$JTA.push(this);
	this.get = function(id) { return document.getElementById(id); }
	this.cr = function(tag) { return document.createElement(tag); }
	var wl = window.location;
	this.uriDomain = (wl.protocol.substr(0, 4) != 'http' ? 'http:' : '')
			+ '//js-kit.com';
	this.uri = this.uriDomain + '/bestof';
	this.utmpl={};

	this.config={};
	this.config.count = 10; // Default 10 items

	this.starWidth = 9;
	this.starHeight = 9;

	var idName = "js-kit-top";

	var target = arguments.length ? arguments[0] : this.get(idName);

	if(target) {

		this.config.skin = target.getAttribute("skin") || '';
		this.config.target = target.getAttribute("target") || '';
		this.config.image1url = target.getAttribute("image1url") || '';
		this.config.image2url = target.getAttribute("image2url") || '';
		this.config.imagesize = target.getAttribute("imagesize") || '';
		if (target.getAttribute("count")) 
			this.config.count = target.getAttribute("count");
		if((this.config.image1url || this.config.image2url) && this.config.imagesize) {
			var dim = this.config.imagesize.match(/(\d+)([^\d]+(\d+))?/);
			if(dim) {
				this.starWidth = dim[1];
				this.starHeight = dim[3] || this.starWidth;
			}
		}

		this.domain = target.getAttribute("domain") || wl.host;
		this.domain = wl.protocol + "//" + this.domain;

		this.title = target.getAttribute("title");
		var cn = target.childNodes;
		for(var n=0;n < cn.length;n++)
			this.utmpl[cn[n].className] = JSKitLib.getOuterHTML(cn[n]);
		if(cn && cn.length) target.innerHTML = "";
		target.style.visibility = "visible";
	} else {
		var els = document.body.getElementsByTagName(idName);
		var oWay = false;
		if(els && els.length) oWay = true;
		else els = document.body.getElementsByTagName("div");
		if(els && els.length) {
			$JTA.shift();
			JSKitLib.map(function(el) {
			  if(oWay || el.className.match(/js-kit-top/))
				new JSTC(el); }, els);
			if($JTA.length) return;
			$JTA.push(this);
		}
		document.write('<div id="'+idName+'"></div>');
		target = this.get(idName);
	}
	target.className = idName;
	target.id = "";

	var self = this;
	self.target = target;

	this.server = function(ext, data) {
		var wl = window.location;
		var sc = self.cr("script");
		sc.setAttribute("charset", "utf-8");

		var domain;
		if (self.domain) {
			domain = self.domain;
		} else {
			domain = wl.protocol + "//" + wl.host;
		}

		sc.src = self.uri + ext
			+ "?ref="
			+ encodeURIComponent(domain + "/")
			+ "&" + data;

		self.target.appendChild(sc);
		return false;
	}
	self.server("-data.js","jx="+self.jpaIndex+"&count="+self.config.count);
}

document.write('<style type="text/css">'

+ ".js-corner { width: 20px; height: 20px; float: left; }"
+ ".js-horz { background: repeat-y; }"
+ ".js-vert { margin: 0 5px; height: 20px; background: repeat-x; }"
+ ".js-content { margin: 0 0; background: repeat; padding: .1em; zoom: 1; }"
+ ".js-content .js-Top { padding: 0; border: none; }"
 
+ ".js-Top { padding: 1em; border: none; }"
+ ".js-TopBg { }" 
+ ".js-topHeader { border-bottom: none; padding-bottom: .2em; position: relative; }"
+ ".js-topTitle { font-size: 11pt; font-family: verdana; }"
+ ".js-topStar { background-repeat: no-repeat; width: 16px; height: 16px; position: absolute; right: 0; top: -4px; z-index: 2; zoom: 1; }"
+ ".js-topItems { font-family: verdana; font-size: 9pt; list-style-type: none; padding-top: .2em; }"
+ ".js-topItems { margin: 0.5em 0 0 0; padding-left: 0em; }"
+ "li.js-topItem { margin: 0.3em; margin-left: 0; padding-left: 0; margin-right: 0; padding-right: 0; background: none;}"
+ ".js-topItemInfo { margin: 0.3em 0; font-size: 8pt; }"
+ ".js-topItemRating { margin: 0 0.8em; }"
+ ".js-topPB { display:none; }"
+ "</style>");


JSTC.prototype.dtSkinTop = function() {

  var skin = this.config.skin;

  var base = this.uriDomain + '/images/top/';
  var vert = "background-image: url('" + base + skin + "_vert.png');";
  var horz = "background-image: url('" + base + skin + "_horz.png');";
  var corner = "background-image: url('" + base + skin + "_all.png');";
  var center = "background-image: url('" + base + skin + "_center.png');";

  var template 
  = '<div style="position: relative; padding-top: 1px;">'
  + '<div class="js-corner" style="' + corner + ' background-position: top left; position: absolute; left: 0;"></div>'
  + '<div class="js-corner" style="' + corner + ' background-position: top right; position: absolute; right: 0;"></div>'
  + '<div class="js-vert" style="' + vert + ' background-position: top"></div>'
  + '<div class="js-horz" style="' + horz + ' background-position: left">'
   + '<div class="js-horz" style="' + horz + ' background-position: right">'
    + '<div class="js-content" style="' + center + '">'
     + this.dtTop
    + '</div>'
   + '</div>'
  + '</div>'
  + '<div class="js-corner" style="' + corner + ' background-position: bottom left; position: absolute; left: 0;"></div>'
  + '<div class="js-corner" style="' + corner + ' background-position: bottom right; position: absolute; right: 0;"></div>'
  + '<div class="js-vert"  style="' + vert + ' background-position: bottom"></div>'
  + '</div>'
  ;

  return template;
}


JSTC.prototype.dtTop
 = '<div class="js-Top">'
 + '<div class="js-TopBg">'
 + '<div class="js-topHeader">'
  + '<div class="js-topStar"></div>'
  + '<div class="js-topTitle">{Title}</div>'
 + '</div>'
 + '<ul class="js-topItems">'
  + '<li class="js-topItem">'
   + '<a class="js-topItemLink" href="{url}">{title}</a>'
   + '<div class="js-topItemInfo">'
   + ' <div class="js-topItemStars"></div>'
   + ' <span class="js-topItemRating">{rating}&nbsp;({votes})</span>'
   + '</div>'
  + '</li>'
 + '</ul>'
 + '</div>'
 + '</div>'

;

JSTC.prototype.addChild = function(to, what) {
	if(arguments.length == 3 && arguments[2])
		to.insertBefore(what, to.firstChild);
	else
		to.appendChild(what);
}
JSTC.prototype.html = function() {
	var div = this.cr("div");
	for(var text = '', i = 0; i < arguments.length; i++)
		text += arguments[i];
	div.innerHTML = text;
	var ch = div.firstChild;
	div = null;
	return ch;
}

JSTC.prototype.mapClass2Object = function(ctl, e) {
	if(e.className) {
		var arr = String(e.className).split(/[ ]+/);
		JSKitLib.map(function(el) { ctl[el] = e }, arr);
	}
	if(e.name) ctl[e.name] = e;
	try {
		var self = this;
		JSKitLib.map(function(child) {
			self.mapClass2Object(ctl, child);
		}, e.childNodes);
	} catch(e){}
	return ctl;
}
JSTC.prototype.gtmpl = function(t) {
	var lowercase = function(a, m) { return String(m).toLowerCase(); }
	t = t.replace(/^[^<]*(<.*>)[^>]*$/m, "$1");
	t = t.replace(/(<[\/]?[A-Z]+)/g, lowercase);
	t = t.replace(/{Label:([^}]*)}/g,function(a,m){return $JTL(m);});
	t = t.replace(/{DOMAIN}/g,this.uriDomain);
	return t;
}
JSTC.prototype.tmpl = function(t, obj) {
	var self = this;
	t = self.gtmpl(t);
	var purify = function(text) {
		var text = String(text).replace(/^[ \s]+|[ \s]+$/, '');
		text = text.replace(/([^&<>\s]{12})([^&<>\s]{12})/g, '$1<wbr></wbr>$2');
		text = text.replace(/[ \t\r\n]+/g, ' ');
		return text;
	}
	t = t.replace(/{([A-Za-z0-9]+)}/g,function(a,m){return obj.hasOwnProperty(m)?purify(obj[m]):'{'+m+'}';});
	return t;
}


JSTC.prototype.displayTop = function(topData, config) {
	var self = this;

	// skin
	if (this.config.skin) {
		var template = this.dtSkinTop();
	} else {
		var template = this.dtTop;        
	}

	var pdiv = this.html(this.tmpl(template, topData));
	var ctls = this.mapClass2Object({}, pdiv);
	self.ctls = ctls;

	// top star
	var topStarURL = 'http://i49.photobucket.com/albums/f276/ayreonauta/flashicon.png';
	var topStar = ctls['js-topStar'];
	JSKitLib.addPNG(topStar, topStarURL);

	var tip = ctls['js-topItems'];
	var tTemplate = tip.innerHTML;
	tip.innerHTML = '';

	var topItem = function(items, idx) {
		var item = items[idx];
		var idiv = self.html(self.tmpl(tTemplate, item));
		var ictls = self.mapClass2Object({}, idiv);
		var link = ictls['js-topItemLink'];
		link.href = item.url;
		if (self.config.target) {
			link.target = self.config.target;
		}    
		var stars = ictls['js-topItemStars'];
		stars.appendChild(item.stars);
		return idiv;
	}

	JSKitLib.map(function(item, i, items) {
		self.addChild(tip, topItem(items, i));
	}, topData.topItems);

	if(config && config.subs) ctls['js-Powered'].style.display = 'none';

	this.addChild(this.target, pdiv);
}

JSTC.prototype.getMiniStars = function(rating, scale) {

	rating = Math.round(rating);

	var fullStar = this.config.image1url || this.uriDomain + '/images/stars/gold-tiny.png';
	var emptyStar = this.config.image2url || this.uriDomain + '/images/stars/gray-tiny.png';

	var stars = JSKitLib.createMiniStarObject(rating, scale, { full: fullStar, empty: emptyStar, width: this.starWidth, height: this.starHeight });

	return stars;
}

JSTC.prototype.newData = function(topData, config) {

	var topItems = JSKitLib.filter(
		function(o) { return (o.type === "TR" && o.title.length); },
			topData.data);
	if(!topItems.length) return;

	// Filter proper number of results
	if (this.config.count < topItems.length)
		topItems.length = this.config.count;

	// Prepare our stars 
	for (var i=0; i < topItems.length; i++) {
		topItems[i].stars = this.getMiniStars(topItems[i].val1, 10);
		topItems[i].rating = Math.round(topItems[i].val1 / 2 * 100)/100;
		topItems[i].votes = topItems[i].val2 + '&nbsp;votos'; 
	}    

	// Remove the common part from title.
	var tiCopy = topItems.slice(0);    
	if(tiCopy.length >= 2) {
		tiCopy.sort(function(a,b) {
			if(a.title < b.title) return -1;
			if(a.title === b.title) return 0; return 1; });
		var a = tiCopy[0].title;
		var b = tiCopy[1].title;
		var c = tiCopy[tiCopy.length - 1].title;
		var l = Math.min(a.length, b.length, c.length);
		var i;
		for(i = 0; i < l; i++) {
			if(a.charAt(i) === b.charAt(i)
			&& a.charAt(i) === c.charAt(i)) {} else break;
		}
		// Do not strip if left with no title
		if ((l - i) > 0) {
			JSKitLib.map(function(a) { a.title = String(a.title).substring(i); }, topItems);
		}
	}

	topData.topItems = topItems;
	topData.Title = this.title || "Más votados";
	this.displayTop(topData, config);
}


