$.fn.media.defaults.caption = false;
$.fn.media.defaults.params= {
	preferMeta:    1,
	wmode: 'transparent'
};

$(function() {
    var page = $("body").attr("id");
	var loader = $('#loading');
	var clockyear = $('.year');
	var clockday = $('.day');
	var clockmonth = $('.month');
	var clockweek = $('.week');
	var clockhour = $('span.h')
	var clockminute = $('span.minute')
	var clocksecond = $('span.seconds')
	var clockampm = $('.ampm');
	var meses = new Array("ENE","FEB","MAR","ABR","MAY","JUN","JUL","AGO","SEP","OCT","NOV","DIC");
	var dias = new Array("DOMINGO","LUNES","MARTES","MIERCOLES","JUEVES","VIERNES","SABADO","DOMINGO");
	var c = readCookie('style');

	if (c) switchStylestyle(c);

	function showtime() {
		var d=new Date();
		var seconds = d.getSeconds();
		var minutes = d.getMinutes();
		var hours   = d.getHours();
		var ampm = (hours >= 12) ? " PM" : " AM";
		var week = dias[d.getDay()];
		var mes = meses[d.getMonth()];
		var dia = d.getDate();
		var anio = d.getFullYear();

		hours = ((hours > 12) ? hours - 12 : hours);
		minutes = ((minutes <  10) ? "0" : "") + minutes;
		seconds = ((seconds <  10) ? "0" : "") + seconds;

		clockyear.text(anio);
		clockday.text(dia);
		clockmonth.text(mes);
		clockweek.text(week);
		clockhour.text(""+hours);
		clockminute.text(""+minutes);
		clocksecond.text(""+seconds);
		clockampm.text(ampm);

		setTimeout(showtime, 1000);
	}
	showtime();

	$.ajaxSetup( { timeout: 10000 } );

 	jQuery().ajaxStart(function() {
        loader.show();
	}).ajaxStop(function() {
        loader.hide();
    });

    jQuery().ajaxError(function(a, b, e) {
        throw e;
    });

    $('#search_query').hint();

    $('#ranking_noticias ul').tabs({fxFade: true,fxSpeed: 'fast'});
    $('#tags ul').tabs({ fxFade: true, fxSpeed: 'fast' });

	$("#votar_noticia").bind("click",
		function() {
			$('#loading p').html('Enviando valoraci&oacute;n, aguarde un segundo por favor...');
			$.ajax({
				type: "GET",
				dataType: "json",
				url: this.href,
				after: function(result) {
					if (result.status) {
						alert("Error: " + result.msg);
					}
				}
			});
			return false;
	});



	$('a#corregir_link').click(function(){
		tb_show('Sugerir correci&oacute;n en esta nota', this.href + '?width=645&height=210');
		return false;
	});

	$('a#enviar_link').click(function(){
		tb_show('Enviar esta nota por correo electr&oacute;nico', this.href + '?width=650&height=280');
		return false;
	});

	$('.ilustracion_noticia').each(function() {
		var title = $(this).attr('alt');
		title = typeof title != 'undefined' ? title: 'Ilustraci&oacute;n:: Riel Fm';
		var img_src = $(this).attr('id');

		$(this).after('<div id="title_' + img_src + '"><p>' + title + '</p></div>');
		$(this).wrap('<a class="ilustracion" href="nimages/' + img_src + '" title="' + title + '"></a>');
	});

	$('.styleswitch').click(function() {
		switchStylestyle(this.getAttribute('rel'));
		return false;
	});

	/*	Comentarios */
	if ( $("[@name='permitir_comentario']").val() == 1) {
		$.get("enviar_comentarios.htm", function(data) {
				$('#comentarios_contenedor').html(data);		
				$.get("_token.php", function(txt) {$("#envio_comentarios_form").append('<input type="hidden" name="ts" value="'+txt+'" />');});
				$('a.ver_politica').click(function(){
					tb_show('Cl&aacute;usula de Privacidad', this.href + '?width=645&height=410');
					return false;
				});
				$("#comentarios_contenedor [@name='nid']").val($("[@name='backtrack']").val());
				var cantidad_comentarios = $('#cant_comentarios').val();
				if ( $('#cant_comentarios').val() > 5 )
				{
					$.getScript('js/jquery.pagination.js', function() {
						$(".pagination").pagination(cantidad_comentarios, {
							num_edge_entries: 2,
							items_per_page: 5,
							num_display_entries: 5,
							link_to: "__id__",
							callback: comentarios_pageselectCallback
						});
					});
				}
				else
				{
					$(".paginacion").hide();
				}

				$("#comentar_link").click(function(){
					$.scrollTo('#comentarios_contenedor', 800);
					return false;
				});

				var validar_comentarios = jQuery("#envio_comentarios_form").validate({
					rules: {
							comentario: {
								required: true,
								minLength: 30
							},
							email: {
								required: true,
								email: true
							},
							nombre: "required",
							acepto_comentario: "required"
					},
					messages: {
						comentario: {
							required: "No debe dejar este campo en blanco",
							minLength: "El comentario debe tener 30 caracteres minimo y 1000 como maximo",
							rangelength: "El comentario debe tener 30 caracteres minimo y 1000 como maximo"
						},
						nombre: "Ingrese nombre completo.",
						email: "Ingrese una direcci&oacute;n v&aacute;lida.",
						acepto_comentario: "Debe aceptar esto"
					},
					submitHandler: function(form) {
						$("#enviar_comentarios").css({disabled:true});
						jQuery(form).ajaxSubmit({
							dataType: "json",
							before: function() { $('#loading p').html('Aguarde un segundo por favor, estamos validando los datos...') },
							success: procesar_comentarios_resultado
						});
					}
				});
		});
	}
	/*
	$(document).bind('keypress', function(e) {
		var key = e.charCode ? e.charCode: e.keyCode ? e.keyCode: 0;
		var url_prev = $('#not_anterior_link').attr('href');
		var url_next = $('#not_siguiente_link').attr('href');
		switch (key) {
			case 37:	// <---
				if (url_prev != undefined) {
					document.location.href = url_prev;
				}
				break;
			case 39: 	// --->
				if (url_next != undefined) {
					document.location.href = url_next;
				}
				break;
		}
	});
	*/
	$('.youtube').media();
	$('.iapv a').media( { width: 150, height: 135} );
	$('.banner_senadorer a').media( { width: 160, height: 197} );
	
	
	$('a.ilustracion').zoomimage({
		controlsTrigger: 'mouseover',
		centered: true,
		border: 4,
		controls: false,
		opacity: 1,
		beforeZoomIn: function(boxID) {
			$('#' + boxID)
			.find('img')
			.css('opacity', 0)
			.animate(
				{'opacity': 1},
				{duration: 500,queue: false}
			);
		},
		beforeZoomOut: function(boxID) {
			$('#' + boxID)
			.find('img')
			.css('opacity', 1)
			.animate(
				{'opacity': 0},
				{duration: 500, queue: false}
			);
		}
	});
});

jQuery.fn.hint = function() {
    return this.each(function() {
        // get jQuery version of 'this'
        var t = jQuery(this);
        // get it once since it won't change
        var title = t.attr('title');
        // only apply logic if the element has the attribute
        if (title) {
            // on blur, set value to title attr if text is blank
            t.blur(function() {
                if (t.val() == '') {
                    t.val(title);
                    t.addClass('blur');
                    t.css("width", "10em");
                }
            });
            // on focus, set value to blank if current value
            // matches title attr
            t.focus(function() {
                if (t.val() == title) {
                    t.val('');
                    t.removeClass('blur');
                    t.css("width", "20em");
                }
            });

            // clear the pre-defined text when form is submitted
            t.parents('form:first()').submit(function() {
                if (t.val() == title) {
                    t.val('');
                    t.removeClass('blur');
                    t.css("width", "20em");
                }
            });

            // now change all inputs to title
            t.blur();
        }
    });
}

function captionizeImages() {
    $("img").each(function() {
        if (this.className == "captioned") {
            $(this).wrap('<div class="imgcontainer"></div>').wrap('<div class="ilustracion"></div>');
            image = new Image();
            image.src = $(this);
            var title = $(this).attr("title");
            $(this).after('<div class="caption">' + title + '</div>');
        }
    })
}

function switchStylestyle(styleName) {
    $('link[@rel*=style][@title]').each(function(i) {
        this.disabled = true;
        if (this.getAttribute('title') == styleName)
			this.disabled = false;
    });
    createCookie('style', styleName, 365);
}

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) {
    if (days)    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else
		var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
// /cookie functions

function comentarios_pageselectCallback(page_id, jq) {
	$('#comentarios_result').text("Mostrando resultados del "+((page_id*5)+1)+"-"+((page_id*5)+5));
	$(".bloque_comentarios").load("comentarios.php",{"page": page_id, nid: $("[@name='backtrack']").val() });
	return false;
}

function cartas_pageselectCallback(page_id, jq) {
	$('#cartas_result').text("Mostrando resultados del "+((page_id*10)+1)+"-"+((page_id*10)+10));
	$(".comentarios").load("cartas_redaccion.php",{page: page_id},
		function() {
			$.scrollTo({top: 0}, 1000);
	});
	return false;
}

function procesar_comentarios_resultado(data) {
	$.ajaxSetup( { timeout: 50000 } );
	if ( data.status == 3 ) {
		$('.error_acepar_comentario').show();
	}
	else {			/// Envio ok u problema interno
		$('#mod_comentarios').html(data.data);
	}
	$.ajaxSetup( { timeout: 10000 } );
}

function procesar_envio_resultado(data) {
	$(".cerrar_corregir").click(tb_remove);
	
	if (data.status == 0) {
		$('.enviando_enviar').hide();
		$('.envio_corregir_ok .data').text(data.data);
		$('.envio_corregir_ok').show();
	}
	else if (data.status == 2) {
		$('.enviando_enviar').hide();
		$("#enviar_noticia_form .cerrar_corregir")
			.after('<input type="button" class="enviar intentar_nuevo" name="intentar_nuevo" value="Intentar de Nuevo"" />')
		$(".intentar_nuevo")
			.bind('click', function() {
				$('.envio_corregir_error').hide();
				$('.enviando_enviar').show();
				$('.intentar_nuevo').remove();
			});

		$('.envio_corregir_error').show();
		$('.envio_corregir_error .data').text(data.data)
		$.get("_token.php", function(txt) {$("#enviar_noticia_form [@name='ts']").val(txt);});

	}
	else if (data.status == 3) {

	}
	else {
		$('.enviando_enviar').hide();
		$('.envio_corregir_error').show();
		$('.envio_corregir_error .data').text(data.data)
	}
}
