//analytics

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-395269-7']);
_gaq.push(['_trackPageview']);

(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

//ladra stuff
function imagesPreload() {
  var images = new Array();
	for(var i = 0; i<arguments.length; i++)
	{
        images[i] = new Image();
        images[i].src = arguments[i];
	}
  return images;  
}

function htmlspecialchars(text) {
  return text.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

cookieMan = {
  defaultDomain : location.host,
  defaultPath : '/',
  setCookie : function(name,value,path,domain,expires) {
    document.cookie = cookieMan.buildCookieString(name,value,path,domain,expires);
  },
  getCookie : function(name) {
    var string = document.cookie;
    var startpos = string.indexOf(name+'=');
    if (startpos != -1) {
      var result = string.indexOf(";",startpos);
      var endpos = (result == -1) ? string.length:result;
      return unescape(string.substring(name.length+1+startpos,endpos));
    }
    return '';
  },
  buildCookieString : function(name,value,path,domain,expires) {
	  var cookie = name+'=';
	  if (value != null) cookie += escape(value);
	  cookie += '; path=' + (path == null) ? cookieMan.defaultPath:path;
	  cookie += '; domain=' + (domain == null) ? cookieMan.defaultDomain:domain;
	  if (expires) cookie += '; expires=' + expires;
	  return cookie;
  },
  deleteCookie : function(name) {
    var pastDate = new Date();
    pastDate.setTime(pastDate.getTime() - 1);
    document.cookie = cookieMan.buildCookieString(name,null,null,null,pastDate.toUTCString());  
  }
}

function imgOnDemand(imgElements,imgHeight) {
	this.activate = function(toPosition) {
		var finalHeight = toPosition + $(window).height();
		for(var i=0; i<imgElements.length; i++) {
			var elem = $(imgElements[i]);
			var pos = elem.position();
			if (pos.top + imgHeight >= toPosition && pos.top < finalHeight) {
				var j=i;
				do {
					elem.after(this.convertToImage(elem));
					elem = $(imgElements[++j]);
				} while(elem.length && elem.position().top < finalHeight);
				var elements = imgElements.slice(0,i);
				imgElements = elements.concat(imgElements.slice(j));
				break;
			}
		}
	}
	this.convertToImage = function(elem) {
		var img = $('<img>');
		img.attr('src',elem.attr('src'));
		img.attr('alt',elem.attr('alt'));
		return img;
	}
}

function modalBox(modalBgClass,modalBoxClass,closeIcon) {
	this.mbox = null;
	this.modalbg = null;
	var self = this;
	if (typeof closeIcon == "undefined") closeIcon = true;
	function createDiv(className) {
		return $(document.createElement('div')).addClass(className);
	}
	function showBg() {
		var bg = createDiv(modalBgClass);
		if (!$.support.opacity && $.browser.msie)
			bg.css('filter','alpha(opacity=60)');

		return bg.appendTo('body').fadeIn(300);
	}
	this.createCloseIcon = function() {
		var self = this;
		createDiv('close-icon').appendTo(this.mbox).bind('click',function() {
			self.close();
		});
	}
	this.show = function(width,height) {
		var mbox;
		if (!this.mbox)
			this.mbox = createDiv(modalBoxClass);
		mbox = this.mbox;
		
		var opVal = mbox.css('opacity');
		mbox.css('opacity',0).appendTo('body').animate({'width':width,'height':height,'opacity':opVal},300,null,function() {
			$(self).trigger('_show');
		});
		this.modalbg = showBg();
		if (closeIcon) this.createCloseIcon();
	}
	this.close = function() {
		if (!this.mbox) return;
		this.modalbg.fadeOut(300,function() { $(this).remove(); });		
		this.mbox.animate({'opacity':0,'width':0,'height':0},300,null,function() { $(self).trigger('_close'); $(this).remove(); });
	}
	this.resize = function(width,height) {
		if (!this.mbox) return;
		this.mbox.animate({'width':width,'height':height},300,null,function() { $(self).trigger('_resize'); });
	}
	this.setContent = function(content) {
		if (!this.mbox) return;
		this.mbox.empty().append(content);
		if (closeIcon) this.createCloseIcon();
	}
}

function imageBox(modalBgClass,modalBoxClass,ajaxicon,imgurl) {
	//Subclass
	var modalBox = new window.modalBox(modalBgClass,modalBoxClass);
	$.extend(this,modalBox);
	//Constructor
	this.ajaxicon = ajaxicon;
	this.imgurl = imgurl;
	var self = this;
	var img = null; //Needs to be global so we can cancel events on close
	this.close = function(transferTo) {
		if (img)
			img.onload = img.onerror = null;
		if (transferTo)
			this.mbox.effect('transfer',{'to':transferTo},300);
		modalBox.close.call(this);
	}
	this.showImage = function(blankWidth,blankHeight) {
		//Start loading ajax image
		blankWidth = parseInt(blankWidth) || 0;
		blankHeight = parseInt(blankHeight) || 0;

		var ajaxloader = new Image;
		ajaxloader.src = this.ajaxicon.src;
		//After loading dialog is already being displayed
		$(modalBox).bind('_show',function() {
			//Load the animated gif
			self.setContent(ajaxloader);
			//Load the final image
			img = new Image;
			img.onload = function() {
				//Calculate available area for the image
				var width = $(window).width() - self.mbox.outerWidth() + self.mbox.width() - blankWidth;
				var height = $(window).height() - self.mbox.outerHeight() + self.mbox.height() - blankHeight;
				
				var dim = calcImageSize(this,width,height);
				
				self.resize(dim.x + blankWidth,dim.y + blankHeight);
				self.setContent(this);
				$(self).trigger('_showImage');
			}
			img.onerror = function() {
				alert('Error al cargar la imagen');
				self.close();
			}
			img.src = self.imgurl;
			//img.src = imgData.pathThumb.replace(/_[a-z](?=\.[a-z]{3,4}$)/,"");
		});
		this.show(this.ajaxicon.width,this.ajaxicon.height); //Show first dialog
	}
	this.prependContent = function(content) {
		this.mbox.prepend(content);
	}
	this.appendContent = function(content) {
		this.mbox.append(content);
	}
	function calcImageSize(image,availWidth,availHeight) {
		//Calculate available area for the image
		var width = availWidth;
		var height = availHeight; //(document.documentElement.clientHeight || $(window).height()) - 20;
		if (image.width > width || image.height > height) { //If bigger than viewport, resize
			if (width / image.width < height / image.height) {
				image.height = (width * image.height / image.width);
				image.width = width;
			}
			else {
				image.width = height * image.width / image.height;
				image.height = height;
			}
		}
		return {'x':image.width,'y':image.height};
	}
}

ladraLib = {
	ajaxloader : {
		src:'/static/img/bigajaxload.gif',
		width:66,
		height:66
	}
}

$(function() {
	imagesPreload(ladraLib.ajaxloader.src);
});

(function($) {
	$.fn.tooltip = function(options) {
		var defaults = {'attr':'title'};
		options = this.extend(defaults,options);
		var tooltipElem;
		var methods = {
			show: function(e) {
				var left = e.pageX;
				var top = e.pageY;
				tooltipElem = $('<div></div>').addClass('tooltip');
				tooltipElem.css({position:'absolute',top:top + 20,left:left});
				tooltipElem.text(this[options.attr]);
				tooltipElem.appendTo('body');
			},
			follow: function(e) {
				tooltipElem.css({top: e.pageY + 20,left: e.pageX});
			},
			remove: function() {
				tooltipElem.remove();
			}
		}
		this.each(function() {
			$(this).mouseover(methods.show).mouseout(methods.remove).mousemove(methods.follow);
		});
		return this;
	}
})(jQuery);

function selectToSlider(selectElem) {
	$(selectElem).hide();
	var slider = $('<div></div>').insertAfter(selectElem);
	var label = $('<span></span>').insertAfter(slider);
	slider.slider({
		value:selectElem.selectedIndex,
		animate:'fast',
		max:selectElem.options.length - 1,
		min:0,
		slide: function(e,ui) {
			selectElem.selectedIndex = ui.value;
			label.text(selectElem.options[ui.value].text);
		}
	});
	label.text(selectElem.options[selectElem.selectedIndex].text);
	return slider;
}

//Facebook
$(function() {
	window.fbAsyncInit = function() {
		  FB.init({appId:'121654201203588',status:false,cookie:true,xfbml:true, channelUrl:'http://ladra.es/static/channel.html'});
	};
  var e = document.createElement('script'); e.async = true;
  e.src = document.location.protocol +
    '//connect.facebook.net/es_ES/all.js';
  document.getElementById('fb-root').appendChild(e);
});

//Twitter
$(function() {
	if ($('.twitter-share-button').length)
		$.getScript('http://platform.twitter.com/widgets.js');
});

//Google +
$(function() {
	if ($('plusone,g\\:plusone').length) {
		window.___gcfg = {lang: 'es',parsetags:'explicit'};
		$.getScript('https://apis.google.com/js/plusone.js',function() { gapi.plusone.go();	});
	}
});

//Races list
$(function() {
	var container = $('#racesPhotoList')[0];
	if (!container) return;
	var elems = ($.browser.msie && $.browser.version < 8) ? document.getElementsByTagName('onimg'):document.getElementsByTagName('ld:onimg');
	var elemsA = [];
	for (var i=0; i<elems.length; i++)
		elemsA[i] = elems[i];
	
	var ion = new imgOnDemand(elemsA,$('#racesPhotoList li li:first').width());
	var callback = function() {
		ion.activate($(window).scrollTop());
		$(window).one('scroll resize',callback);
	}
	$(window).one('scroll resize',callback).trigger('scroll');
});

//Races suggest
$(function() {
	if (typeof suggest == "undefined") return;
	function getSuggestedRaces(string,successCb,errorCb) {
		$.ajax({
			url:'/ajax/suggest/?in='+encodeURIComponent(string),
			dataType: 'json',
			success: successCb,
			error: errorCb
		});
	}
	$('.raceSuggest').each(function() {
		suggest(this.id,3,false,'suggestBox',getSuggestedRaces);
	});
});
