/**
 * Funcion Ajax
 *  @param url accion a llamar
 */

function refreshAdShopping(urlAction, callback){
    $.ajax({
        type: "GET",
        url: urlAction,
        cache: false,
        success: function(data){
            var adShoppingAjax= $("#adShoppingAjax");
            adShoppingAjax.html(data);
            var menuAjax = $("#menuAjax");
            var menuAjaxAnchor = $("#menuAjax a");
            var numeroProductos = $("#adShoppingAjax .box-cesta-cont").length;
            var estadoCesta = numeroProductos > 0 ? 'on' : '';
            menuAjax.html('<div class="cesta ' + estadoCesta + '"><span>' + numeroProductos + '</span><a href="' + menuAjaxAnchor.attr("href") + '" onclick="this.blur();" title="ver mi cesta">ver mi cesta</a></div>');
            if(callback)
                callback(data);
        },
        error:function (XMLHttpRequest, textStatus, errorThrown){
            if (XMLHttpRequest.status == 450){
                //alert("entra, poner el link con '?ampliacionCurso=si'");
            }
        }
    });
}

function refreshDetalle(urlAction, callback){
        $.ajax({
        type: "GET",
        url: urlAction,
        cache: false,
        success: function(data){
            var detalleCestaAjax= $("#detalleCestaAjax");
            detalleCestaAjax.html(data);
            var menuAjax= $("#menuAjax");
            var menuAjaxAnchor = $("#menuAjax a");
            var numeroProductos = $("#detalleCestaAjax .box-cesta-2").length;
            var estadoCesta = numeroProductos > 0 ? 'on' : '';
            menuAjax.html('<div class="cesta ' + estadoCesta + '"><span>' + numeroProductos + '</span><a href="' + menuAjaxAnchor.attr("href") + '" onclick="this.blur();" title="ver mi cesta">ver mi cesta</a></div>');
            if(callback)
                callback(data);
        }
    });
}

function addProducto(productoId) {
    var producto = $("#productoId_" + productoId);
    if (producto.length > 0) {
        producto.fadeOut(0, function() {
            producto.fadeIn(500);
        });
    } else {
        refreshAdShopping('/addProducto.action?videocursoId='+productoId, function() {
            var avisos = $("#productoId_" + productoId + ", #precio_total b, #menuAjax span");
            avisos.fadeOut(0, function() {
                avisos.fadeIn(500);
            });
        });
    }
}

function removeProducto(productoId) {
    var numeroProductos = $("#adShoppingAjax .box-cesta-cont").length;
    if(numeroProductos > 1) {
        var productoDiv = $("#productoId_" + productoId);
        productoDiv.fadeOut(500, function() {
            refreshAdShopping('/removeProducto.action?videocursoId='+productoId, function() {
                var avisos = $("#precio_total b, #menuAjax span");
                avisos.fadeOut(0, function() {
                    avisos.fadeIn(500);
                });
            });
        });
    } else {
        refreshAdShopping('/removeProducto.action?videocursoId='+productoId, function() {
            var avisos = $("#cesta_vacia, #precio_total b, #menuAjax span");
            avisos.fadeOut(0, function() {
                avisos.fadeIn(500);
            });
        });
    }
}

function removeProductoDetalle(productoId) {
    var numeroProductos = $("#detalleCestaAjax .box-cesta-2").length;
    if(numeroProductos > 1) {
        var productoDiv = $("#productoId_" + productoId);
        productoDiv.fadeOut(500, function() {
            refreshDetalle('/removeProductoDetalle.action?videocursoId='+productoId, function() {
                var avisos = $("#precio_subtotal, #precio_total, #menuAjax span");
                avisos.fadeOut(0, function() {
                    avisos.fadeIn(500);
                });
            });
        });
    } else {
        refreshDetalle('/removeProductoDetalle.action?videocursoId='+productoId, function() {
            var avisos = $("#detalleCestaAjax, #precio_subtotal, #precio_total, #menuAjax span");
            avisos.fadeOut(0, function() {
                avisos.fadeIn(500);
            });
        });
    }    
}


function convertAmountCurrency(country, amount, callback){
    $.ajax({
        type: "GET",
        url: "crossdomain?url="+ escape("http://download.finance.yahoo.com/d/quotes.csv?s=EUR" + country + "=X&f=l1&e=.csv"),
        cache: false,
        success: function(change){
            var amountConverted = Math.round(parseFloat(change) * parseFloat(amount) * 100) / 100 ;
            if(callback)
                callback(change, amountConverted);
        }        
    });
}

function cleanCesta() {
    refreshDetalle('cleanCesta.action');
}


/* Llamada Asincrona (OpenAds) */
/*
function showCountryText(url, elementId){
    // Obtenemos el codigo por AJAX. Llamada NO bloqueante
    var sUrl = "crossdomain?url="+escape(url);
        $.ajax({
        type: "GET",
        url: sUrl,
        cache: false,
        success: function(data){
            var div = $("#"+elementId);
            var aux = data;
            var index = aux.lastIndexOf("document.write");
            // se ha encontrado coincidencia
            if((index)&&(index>0)) {
                // eliminamos esa parte de la respuesta
                aux = aux.substring(0,index);
                // hacemos pasar al evaluador de javascript para que interprete la respuesta, ya que openads
                // declara primero una variable y luego le asigna  el codigo html del banner
                aux = eval(unescape(aux));
                // insertamos el html puro en el elemento de respuesta (elementoid)
                if(aux !== undefined){
                    // Existe un banner linkado a esa zona
                    div.html(aux);

                    div.fadeOut(0, function() {
                        div.fadeIn(500);
                    });
                }
            }
        }
    });
}
 */

/* Llamada Sincrona (OpenAds-necesaria para la geolocalizacion) */
function showCountryText(url, elementId){
    if (!document.phpAds_used) document.phpAds_used = ',';
    phpAds_random = new String(Math.random()); phpAds_random = phpAds_random.substring(2,11);
    var code = "<script language='JavaScript' type='text/javascript' src='";
    code +=""+url+"&amp;n="+phpAds_random;
    code +="'><" + "/script>";
    document.write(code);
}

function getTweets(){
    $.ajax({
        type: "GET",
        url: "getTweets.action",
        cache: false,
        success: function(data){
            var div = $("#twitterDiv");
            div.html(data);
        }
    });
}
