String.implement({
	str_replace : function(search, replace) {
		var s = this;
		var ra = r instanceof Array, sa = s instanceof Array;
		var f = [].concat(search);
		var r = [].concat(replace);
		var i = (s = [].concat(s)).length;
		var j = 0;
    
		while (j = 0, i--) {
			if (s[i]) {
				while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
			}
		}

		return sa ? s : s[0];
	}
});

Element.Events.clickout = {
	base : 'click',
	condition : function(event) {
		if (event.target.href) return true;
		event.stop();
		return false;
	},
  		
	onAdd : function(fn) {
		$(this.getDocument().body).addEvent('click', fn);
	},

	onRemove : function(fn) {
  		$(this.getDocument().body).removeEvent('click', fn);
	}
};

var HODEI = {};

HODEI.Images = {
	init : function() {
		$(document.body).getElements('a[rel=box]').each(function(el) {
			el.set({
				events : {
					click : function(e) {
						new Event(e).stop();
						
						new PhotoBox({
							picture : this.href,
							duration: 3
						});
					}
				}
			});
		});
	}
};

HODEI.Home = {
	init : function() {
		if($('news')) {
			$('news').set({
				styles : {
					opacity : 0.8
				}
			});
		}
		
		if($('show')) {
			var myShow = new Slideshow('show', data, {
		    	captions: false, 
		    	controller: false, 
		    	height: 490, 
		    	hu: 'imgs/portadas/',
		    	width: 950,
		    	delay: 5000
			});
		}
	}
};

var container = null;
	
function showThumbs(r) {
	var images = [];
	var info = [];
	
	for(var i = 0; i < r.length; i++) {
		images.push(r[i].thumbnail_large);
		info.push({
			title : r[i].title,
			url: r[i].url,
			clip_id: r[i].clip_id,
			caption: r[i].caption,
			upload_date: r[i].upload_date,
			thumbnail_small: r[i].thumbnail_small,
			thumbnail_medium: r[i].thumbnail_medium,
			thumbnail_large: r[i].thumbnail_large,
			user_name: r[i].user_name,
			user_url: r[i].user_url,
			user_thumbnail_small: r[i].user_thumbnail_small,
			user_thumbnail_large: r[i].user_thumbnail_large,
			stats_number_of_likes: r[i].stats_number_of_likes,
			stats_number_of_plays: r[i].stats_number_of_plays,
			stats_number_of_comments: r[i].stats_number_of_comments,
			duration: r[i].duration,
			width: r[i].width,
			height: r[i].height,
			tags: r[i].tags				
		});
	}
			
	new Asset.images(images, {
		onComplete : function() {
			$('loading').set({
				styles : {
					display : 'none'
				}
			});
		},
		
		onProgress : function(photo, index) {	
			new Asset.image(info[index].thumbnail_large, {
				onload : function(picture) {
					picture.setStyle('opacity', 0);
					
					var item = new Element('li');
					var link = new Element('a', {
						href : info[index].clip_id,
						rel  : 'lightbox',
						events : {
							click : function(e) {
								new Event(e).stop();
								
								new VimeoBox({
									videoInfo : info[index],
									server : 'vimeo.com',
									show_title : 0,
									show_byline : 0,
									show_portrait : 0,
									color : '0x000000',
									fullscreen : 1,
									duration: 3
								});
							}
						}
					}).grab(picture);
					
					item.adopt(link);						
					container.adopt(item);		
					picture.fade('in');
				}
			});
		}
	});
}

HODEI.Videos = {
	init : function() {
		if($('gallery')) {
			container = $('gallery').getElements('ul')[0];
			var script = new Element('script', {
				src : 'http://www.vimeo.com/api/hodeicollazo/clips.json?callback=showThumbs'
			})
			$(document.head).adopt(script);
		}
	}
};

HODEI.Photos = {
	init : function() {
		if($('photoGallery')) {
			var container = $('photoGallery').getElements('ul')[0];
					
			new Asset.images(images, {
				onComplete : function() {
					$('loading').set({
						styles : {
							display : 'none'
						}
					});
				},
				
				onProgress : function(photo, index) {	
					new Asset.image(images[photo], {
						onload : function(picture) {
							picture.setStyle('opacity', 0);
							
							var item = new Element('li');
							var link = new Element('a', {
								href : picture.get('src').str_replace('_s.jpg', '_b.jpg'),
								rel  : 'lightbox',
								events : {
									click : function(e) {
										new Event(e).stop();
										
										new PhotoBox({
											picture : this.href,
											duration: 3
										});
									}
								}
							}).grab(picture);
							
							item.adopt(link);						
							container.adopt(item);		
							picture.fade('in');
						}
					});
				}
			});
		}
	}
};


HODEI.Visitas = {
	init : function() {
		if($('commentsForm')) {
			$('commentsForm').set({
				events : {
					submit : this.sendcomment.bindWithEvent(this)
				}
			});
		}
		
		if($('ok')) {
			$('ok').set({
				styles : {
					display : 'none'
				}
			});
		}			
		
		if($('fail')) {
			$('fail').set({
				styles : {
					display : 'none'
				}
			});
		}
	},
	
	sendcomment : function(e) {
		new Event(e).stop();
		
		var fail = [];
		
		if($('name').value.length == 0) {
			fail.include(true);
		}
		
		if($('message').value.length == 0) {
			fail.include(true);
		}

		
		if(!/^[A-Za-z\.][A-Za-z0-9_\.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/.test($('email').value)) {
			fail.include(true);
		}
		
		if(fail.length == 0) {
			this.insertComment({
				name : $('name').value,
				message : $('message').value
			});
					
			$('commentsForm').send();
		} else {
			$('fail').set({
				styles : {
					display : 'block',
					opacity : 0
				}
			});
			$('fail').fade('in');
		}
	},
	
	insertComment : function(o) {
		var strDate = this.date('d \\d\\e F \\d\\e Y', (new Date()).getTime()/1000);
		
		var list = $('commentsList').getElement('ul');
		
		var item = new Element('li');
		var small = new Element('small', {
			text : 'Publicado el ' + strDate
		});
		var por = new Element('span', {
			text : ' port '
		});
		var span = new Element('span', {
			text : o.name
		}).addClass('by');
		
		var p = new Element('p', {
			text : o.message
		});
		
		item.adopt([small, por, span, p]);
		item.inject(list, 'top');
		
		// Mensaje de insercción correcta de comentario
		$('fail').set({
			styles : {
				display : 'none',
				opacity : 0
			}
		});
		$('ok').set({
			styles : {
				display : 'block',
				opacity : 0
			}
		});
		$('ok').fade('in');
	},
	
	date : function date(format, timestamp) { 
		var jsdate=(
			(typeof(timestamp) == 'undefined') ? new Date() : // Not provided
        	(typeof(timestamp) == 'number') ? new Date(timestamp*1000) : // UNIX timestamp
        	new Date(timestamp) // Javascript Date()
    	); // , tal=[]
    	var pad = function(n, c){
        	if( (n = n + "").length < c ) {
				return new Array(++c - n.length).join("0") + n;
        	} else {
            return n;
        	}
    	};
    	var _dst = function (t) {
        	// Calculate Daylight Saving Time (derived from gettimeofday() code)
        	var dst=0;
        	var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
        	var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
			var temp = jan1.toUTCString();
        	var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        	temp = june1.toUTCString();
        	var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));
        	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
        	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
 
        	if (std_time_offset === daylight_time_offset) {
				dst = 0; // daylight savings time is NOT observed
        	}
        	else {
				// positive is southern, negative is northern hemisphere
            var hemisphere = std_time_offset - daylight_time_offset;
            if (hemisphere >= 0) {
                std_time_offset = daylight_time_offset;
            }
            dst = 1; // daylight savings time is observed
        	}
        	return dst;
    	};
    	var ret = '';
    	var txt_weekdays = ["Domingo","Lunes","Martes","Miércoles",
        "Jueves","Viernes","Sábadp"];
    	var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    	var txt_months =  ["", "Enero", "Febero", "Marzo", "Abril",
        "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre",
        "Diciembre"];
 
    	var f = {
        	// Day
			d: function(){
				return pad(f.j(), 2);
			},
			D: function(){
				var t = f.l();
				return t.substr(0,3);
			},
         j: function(){
				return jsdate.getDate();
			},
			l: function(){
				return txt_weekdays[f.w()];
			},
			N: function(){
				return f.w() + 1;
			},
			S: function(){
				return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
			},
			w: function(){
				return jsdate.getDay();
			},
			z: function(){
				return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
			},
 
        	// Week
			W: function(){
				var a = f.z(), b = 364 + f.L() - a;
				var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
 
				if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
					return 1;
				} 
				if(a <= 2 && nd >= 4 && a >= (6 - nd)){
					nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
					return date("W", Math.round(nd2.getTime()/1000));
				}
				return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
			},
 
        	// Month
			F: function(){
				return txt_months[f.n()];
			},
			m: function(){
				return pad(f.n(), 2);
			},
			M: function(){
				var t = f.F();
				return t.substr(0,3);
			},
			n: function(){
				return jsdate.getMonth() + 1;
			},
			t: function(){
				var n;
				if( (n = jsdate.getMonth() + 1) == 2 ){
					return 28 + f.L();
				}
				if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
					return 31;
				}
				return 30;
			},
 
        	// Year
			L: function(){
				var y = f.Y();
				return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
			},
			o: function(){
				if (f.n() === 12 && f.W() === 1) {
					return jsdate.getFullYear()+1;
				}
				if (f.n() === 1 && f.W() >= 52) {
					return jsdate.getFullYear()-1;
				}
				return jsdate.getFullYear();
			},
			Y: function(){
				return jsdate.getFullYear();
			},
			y: function(){
				return (jsdate.getFullYear() + "").slice(2);
			},
 
        	// Time
			a: function(){
				return jsdate.getHours() > 11 ? "pm" : "am";
			},
         A: function(){
         	return f.a().toUpperCase();
			},
         B: function(){
         	// peter paul koch:
            var off = (jsdate.getTimezoneOffset() + 60)*60;
            var theSeconds = (jsdate.getHours() * 3600) +
            						(jsdate.getMinutes() * 60) +
                              jsdate.getSeconds() + off;
				var beat = Math.floor(theSeconds/86.4);
				if (beat > 1000) {
					beat -= 1000;
				}
            if (beat < 0) {
            	beat += 1000;
            }
				if ((String(beat)).length == 1) {
					beat = "00"+beat;
				}
				if ((String(beat)).length == 2) {
            	beat = "0"+beat;
				}
				return beat;
			},
         g: function(){
         	return jsdate.getHours() % 12 || 12;
			},
         G: function(){
         	return jsdate.getHours();
			},
			h: function(){
         	return pad(f.g(), 2);
			},
         H: function(){
         	return pad(jsdate.getHours(), 2);
			},
         i: function(){
         	return pad(jsdate.getMinutes(), 2);
			},
			s: function(){
				return pad(jsdate.getSeconds(), 2);
			},
			u: function(){
         	return pad(jsdate.getMilliseconds()*1000, 6);
			},
 
			// Timezone
			e: function () {
				return 'UTC';
			},
			I: function(){
				return _dst(jsdate);
			},
			O: function(){
				var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
				t = (jsdate.getTimezoneOffset() > 0) ? "-"+t : "+"+t;
				return t;
			},
			P: function(){
				var O = f.O();
				return (O.substr(0, 3) + ":" + O.substr(3, 2));
			},
			T: function () {
                return 'UTC';
			},
			Z: function(){
				return -jsdate.getTimezoneOffset()*60;
			},
 
        	// Full Date/Time
			c: function(){
				return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
			},
			r: function(){
				return f.D()+', '+f.d()+' '+f.M()+' '+f.Y()+' '+f.H()+':'+f.i()+':'+f.s()+' '+f.O();
			},
			U: function(){
				return Math.round(jsdate.getTime()/1000);
			}
    	};
 
		return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        	if(t != s) {
				// escaped
            ret = s;
        	} else if( f[s] ){
            // a date function exists
            ret = f[s]();
        	} else{
            // nothing special
            ret = s;
        	}
        	return ret;
		});
	}
};


window.addEvent('domready', function() {
	$each(HODEI, function(value) {value.init();})
});
