$(document).ready(function () {
	$(document).pngFix();
	
	var baseUrl = $("#baseurl").val();
	
	if ($("h1.sarreratrigger").length) {
		$("div.sarrerahide").hide();
		if ($("div.intro div.sarrerahide").length) {
			$("div.intro").css("border-bottom-width", "1px");
		}
		$("h1.sarreratrigger").live("click", function () {
			if ($("div.intro div.sarrerahide").length) {
				$("div.sarrerahide").show();
				$("div.sarrerahide").attr("class", "sarrerashow");
				$("div.intro").css("border-bottom-width", "0.5em");
			} else {
				$("div.sarrerashow").hide();
				$("div.sarrerashow").attr("class", "sarrerahide");
				$("div.intro").css("border-bottom-width", "1px");
			}
			
		});
	}
	
	// Cálculo automático de los precios en el carrito de la compra
	if ($("#shoppingcart_form").length) {
		//Cogemos todos los inputs cuyo nombre empieza por "books[" para coger las cantidades por libro
		var shopcart_update = function () {
			var total = 0;
			var subtotal = 0;
			var discount = 0;
			var books = $("input[name^='books[']");
			var discountValue = $("#discount").val();
			
			$.each(books, function () {
				var name = $(this).attr("name").match(/books\[(.*)\]/);
				subtotal += $(this).val() * $("input[name='books_price[" + name[1] + "]']").val();
				
			});
			total = Math.round((subtotal - discount) * 100) / 100;

			var subtotalNum = new Number(subtotal);
			discount = new Number(Math.round(subtotal * discountValue) / 100);
			total = new Number(Math.round((subtotal - discount) * 100) / 100);
			
			$("#shoppingcart_subtotal").text(subtotalNum.toLocaleString() + "€");
			$("#shoppingcart_discount").text(discount.toLocaleString() + "€");
			$("#shoppingcart_total").text(total.toLocaleString() + "€");
			
			$.post(window.location.href, $("#shoppingcart_form").serialize() + '&accion=eguneratu',function(data){return false});
		};

		var books = $("input[name^='books[']");

		books.live('click', function () {
			$(this).select();
		});
		$("#eguneratu").remove();
		books.change(shopcart_update);
	}
	
	//Fotos de prentsa_bulegoa
	$(".irudi_korporatiboa_wrapper a").click(function () {
		var url = $(this).attr('href').replace('thumb', 'image');
		var title = $(this).attr('title');
		var elem = '<div><img src="' + url + '"/></div>';
		
		$(elem).dialog({
			modal: true,
			close: function () {
				$(elem).remove();
				$(this).dialog('destroy');
			},
			width: "",
			resizable: false,
			title: title
		});
		
		return false;
	});
	
	if ($("input[name=email]").length) {
		$("input[name=email]").live('click', function () {
			if ($(this).val() == 'e-mail') {
				$(this).select();
			}
		});
	}
	
	if ($("input[name=query]").length) {
		$("input[name=query]").live('click', function () {
			if ($(this).val() == 'Sartu testua') {
				$(this).select();
			}
		});
	}
	
	if ($("input[name=title]").length) {
		$("input[name=title]").live('click', function () {
			if ($(this).val() == 'izenburua?') {
				$(this).select();
			}
		});
	}
	
	if ($("input[name=author]").length) {
		$("input[name=author]").live('click', function () {
			if ($(this).val() == 'idazlea?') {
				$(this).select();
			}
		});
	}
	
	if ($("#gerokoGertaerak").length) {
		/*
		$("#gerokoGertaerak").parent()
		.append("<p><a>Ikusi hurrengo hilabetetakoak</a></p>");
		*/
		$("#gerokoGertaerak").hide();
	}
	
	if ($("a.print").length) {
		$("a.print").click(function () {
			window.print();
		});
	}
	
	if ($(".eposta").length) {
		$(".eposta").each(function (i, val) {
			$(this).text($(this).text().replace(" abildua ", "@").replace(" puntu ", "."));
		});
	}

	if ($('a[rel="external"]').length) {
		$('a[rel="external"]').each(function (i, val) {
			$(this).attr("target", "_blank");
		});
	}
	
	if ($('input[name=urteko_kuota]').length) {
        $('#laguntza').parent().hide();
	    $('input[name=urteko_kuota]').change(function () {
	        if ($(this).attr('id') === 'urteko_kuota-laguntzailea') {
	            if ($(this).attr('checked')) {
	                $('#laguntza').parent().fadeIn();
	            } 
	        } else {
                if ($(this).attr('checked')) {
                    $('#laguntza').parent().fadeOut();
                }
	        }
	    });
    }

	/**
	 * valores de #ikasketa_lana:
	 * 1: ikaslea
	 * 2: langilea
	 * 3: langabea
	 * 4: erretiratua/minusbaliatua
	 */
    if ($('#ikasketa_lana').length) {
        
        $('#lan_mota').parent().parent().hide();
        $('#ikasketa_mota').parent().parent().hide();
        switch ($('#ikasketa_lana').val()) {
            case '1':
                $('#ikasketa_mota').parent().parent().show();
                break;
            case '2':
                $('#lan_mota').parent().parent().show();
                break;
        }
        
        $('#ikasketa_lana').change(function () {
            switch ($(this).val()) {
                case '1':
                    $('#ikasketa_mota').parent().parent().show();
                    $('#lan_mota').parent().parent().hide();
                    break;
                case '2':
                    $('#ikasketa_mota').parent().parent().hide();
                    $('#lan_mota').parent().parent().show();
                    break;
                default:
                    $('#ikasketa_mota').parent().parent().hide();
                    $('#lan_mota').parent().parent().hide();
                    break;
            }
            if ($(this).val() == '2') {
                $('#lan_mota').parent().parent().show();
            } else {
            }
        });
    }

    if ($('#non_ezagutu').length) {
        $('#laguntza').parent().hide();
        $('input[name=urteko_kuota]').change(function () {
            if ($(this).attr('id') === 'urteko_kuota-laguntzailea') {
                if ($(this).attr('checked')) {
                    $('#laguntza').parent().fadeIn();
                } 
            } else {
                if ($(this).attr('checked')) {
                    $('#laguntza').parent().fadeOut();
                }
            }
        });
    }
    
    var numPagItems = 10;
    
    function medioetanPaginatorCallback(page_index, jq){
        var initNum = numPagItems * page_index;
        $('#medioetanShown').empty();
        for (var i = 0; i <  numPagItems; i++) {
            var new_content = $('#medioetanHidden p:eq('+(page_index * numPagItems + i)+')').clone();
            $('#medioetanShown').append(new_content);
        }
        return false;
    }
    
    function oharrakPaginatorCallback(page_index, jq){
        var initNum = numPagItems * page_index;
        $('#oharrakShown').empty();
        for (var i = 0; i <  numPagItems; i++) {
            var new_content = $('#oharrakHidden li:eq('+(page_index * numPagItems + i)+')').clone();
            $('#oharrakShown').append(new_content);
        }
        return false;
    }
    
    function irudiKorporatiboaPaginatorCallback(page_index, jq){
        var numPagItems = 4;
        var initNum = numPagItems * page_index;
        $('#irudiKorporatiboaShown').empty();
        for (var i = 0; i <  numPagItems; i++) {
            var new_content = $('#irudiKorporatiboaHidden div.irudi_korporatiboa_wrapper:eq('+(page_index * numPagItems + i)+')').clone();
            $('#irudiKorporatiboaShown').append(new_content);
        }
        return false;
    }
    
    // count entries inside the hidden content
    var numMedioetanEntries = $('#medioetanHidden p').length;
    if (numMedioetanEntries > 0) {
        // Create content inside pagination element
        $("#medioetanPagination").pagination(numMedioetanEntries, {
            callback: medioetanPaginatorCallback,
            items_per_page: numPagItems,
            next_text: ' »',
            prev_text: '« '
        });
    }
    
    // count entries inside the hidden content
    var numOharrakEntries = $('#oharrakHidden li').length;
    if (numOharrakEntries > 0) {
        // Create content inside pagination element
        $("#oharrakPagination").pagination(numOharrakEntries, {
            callback: oharrakPaginatorCallback,
            items_per_page: numPagItems,
            next_text: ' »',
            prev_text: '« '
        });
    }
    
    // count entries inside the hidden content
    var numIrudiKorporatiboaEntries = $('#irudiKorporatiboaHidden div.irudi_korporatiboa_wrapper').length;
    if (numIrudiKorporatiboaEntries > 0) {
        // Create content inside pagination element
        $("#irudiKorporatiboaPagination").pagination(numIrudiKorporatiboaEntries, {
            callback: irudiKorporatiboaPaginatorCallback,
            items_per_page: 4,
            next_text: ' »',
            prev_text: '« '
        });
    }
    

	
});
