var jq = jQuery.noConflict();
var nowait = false;
/*#####UTILITY funzioni che hanno un utilità generica*/
//funzione che data una url ti porta fuori le variabili
function getUrlVars(url)
{
    var vars = [], hash;

    var hashes;
    //Nel caso in cui sia passata la url non prendo quella del location
    if(url!=null){
        hashes = url.slice(url.indexOf('?') + 1).split('&');
    }

    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/*##### DOCUMENT READY functions*/
jq('document').ready(function(){
    jq('body').append('<div id="loadingDiv">'+
        '<div id="loadingDivModal"></div>'+
        '<div id="loadingDivContent">'+
        '<img src="/skin/frontend/beadsnco2011/default/images/ajax-loader-img.gif" style="margin-right: 5px;" />'+
        '</div></div>'
    );

    jq('#loadingDiv')
    .ajaxStart(function() {
        if(nowait != true){
            jq(this).fadeIn();
        }
    })
    .ajaxStop(function() {
        jq(this).fadeOut();
    });

});

function hideAjaxWait(){
    jq('#loadingDiv').fadeOut();
}

/*##### Funzioni per rendere il CATEGORY LISTING AJAX funzionante totalmente */

function makeCategoryListingAjax(limitedObj){
    var links = null;
    
    if(limitedObj != null){
        links = limitedObj.find(".impaginato a");
    }else{
        links = jq(".impaginato a");
    }
    
    //imposto l'ajax per gli href della paginazione
    links.each(function(){
        if(jq(this).attr("href") != "javascript:void(0)" ){
            jq(this).attr("data-href", jq(this).attr("href"));
            jq(this).attr("href", "javascript:void(0)");
        }
        //alert('pagina');
        jq(this).click(function(){
            var pagina = getUrlVars(jq(this).attr("data-href"));

            //traggo l'ordinamento in quanto è una dannata url
            var ordinamento = jq(this).parents(".sintra_category_listing_content").find("select option:selected").val();

            ordinamento = getUrlVars(ordinamento);

            var categoria = jq(this).parents(".sintra_category_listing_content").find(".category_id").val();
            
            loadCategoryAjax(jq(this).parents(".sintra_category_listing"),categoria, pagina["p"], ordinamento["order"],ordinamento["dir"] );
        });
    });

    //imposto l'ajax per la dropdown di ordinamento'
    jq(".sintra_category_listing_content .barra-lista-dx select").attr("onchange", "");
    jq(".sintra_category_listing_content .barra-lista-dx select").change(function(){
        var data =  getUrlVars(jq(this).children("option:selected").val());
        var categoria = jq(this).parents(".sintra_category_listing_content").find(".category_id").val();
        //alert('ordinamento');
        loadCategoryAjax(jq(this).parents(".sintra_category_listing"),categoria, "", data["order"],data["dir"] );
    });

    //imposto l'ajax per la regola di ordinamento (ascendente, discendente)
    jq(".sintra_category_listing_content .barra-lista-dx a").each(function(){
        if(jq(this).attr("href") != "javascript:void(0)" ){
            jq(this).attr("data-href", jq(this).attr("href"));
            jq(this).attr("href", "javascript:void(0)");
        }
        //alert('direzione');
        jq(this).click(function(){
            var data =  getUrlVars(jq(this).attr("data-href"));
            var categoria = jq(this).parents(".sintra_category_listing_content").find(".category_id").val();
            loadCategoryAjax(jq(this).parents(".sintra_category_listing"),categoria, "", data["order"],data["dir"] );
        });
    });
}

/* Funzione di inserimento nel carrello ajax
 * la insertOkFunction è la funzione che viene richiamata dopo l'inserimento
 * questo permette di customizzare le operazioni da fare dopo a partire dal template
 */
function addCartAjax(currentProduct, product_id, qty, otherParams,resultType, insertOkFunction){
    var params = "product_id=" + product_id + "&qty=" + qty+"&resulttype="+resultType;
    for (var i=0; i<otherParams.length; i++) { 
      params = params+"&"+otherParams[i][0]+"="+otherParams[i][1];
    } 
    //http://beadsnco.localhost/checkout/cart/add/uenc/aHR0cDovL2JlYWRzbmNvLmxvY2FsaG9zdC9iYXNlLXJlZ29sYWJpbGUtcGVyLWFuZWxsby1jb24tbWFnbGluYS5odG1s/product/3561/
    var url = "/addcartajax/?"+params;
    url = encodeURI(url);
    jq("#shopping").load(url,
        function(data, textStatus, jqXHR){
            if (textStatus == "error"){
                alert("There was an error adding this item to your cart.  Please call customer service for assistance.", "Error");
                return;
            }

            if (data.result == "error"){
                alert("Sorry, an error occurred while adding the item to your cart.  The error was: '" + data.message + "'");
                return;
            }else{
                //alert("Prodotto inserito con successo");
                insertOkFunction.call(currentProduct);         
            }
        }); // end add to cart
}

//funzione per caricare realmente una categoria in un contenitore
function loadCategoryAjax($destination, category_id, pagina, ordinamento,direzione, callback){
    if(pagina == null || pagina == undefined || pagina == "" ){
        pagina = 1;
    }
    var params = "category_id="+category_id+"&p="+pagina+"&order="+ordinamento+"&dir="+direzione;
    var url = "/categorylistajax/?"+params+" #sintra_category_listing_content";
    jq($destination).load(url,function(data, textStatus, jqXHR){
        if (textStatus == "error"){
            alert("There was an error adding this item to your cart.  Please call customer service for assistance.", "Error");
            return;
        }
        if (data.result == "error"){
            alert("Sorry, an error occurred while adding the item to your cart.  The error was: '" + data.message + "'");
            return;
        }else{              
            makeCategoryListingAjax();
            makeProductsInListAjax();                
            hideAjaxWait();
            if(typeof callback == 'function')    callback.call();
        }    
    });
    
}


/*#### FUNZIONI JQUERY CUSTOM*/
//funzione per rendere ajax l'inserimento nel carrello dei prodotti nell'elenco prodotti
jq.fn.makeAddCartAjax = function(insertOkFunction) {
    jq(this).click(function(e){
        var isToInsert = true;
        if(typeof(productAddToCartForm) !== 'undefined') {
            isToInsert = productAddToCartForm .validator.validate();
        }
        
        if(isToInsert){
            /*Gestione dello stock
                var stockStatus = jq("option:selected", colorSelector).attr("stockstatus");
                if (stockStatus == "out of stock"){
                    showDialog("Sorry, that colour is currently unavailable.", "Out of Stock")
                    return false;
                }*/

            //inserisco anche i parametri aggiuntivi per i prodotti configurabili
            var otherParams = new Array();
            var qty = 1;
            var product_id;
            //cerco eventuali select dei configurabili
            jq('select, input, textarea').each(
                function(){
                    var arr = new Array();
                    arr[0] = jq(this).attr("name");
                    arr[1] = jq(this).val();
                    if(arr[0]!="qty" && arr[0]!="product"){
                        otherParams.push(arr);
                    }else{
                        if(arr[0]=="qty" ){
                            qty = arr[1];
                        }
                        if(arr[0]=="product"){
                            product_id = arr[1];
                        }
                    }

                }
            );

            //caso del vorrei creare
            if(product_id == undefined) product_id = jq(this).attr("data-num");

            addCartAjax(this, product_id, qty,otherParams, "cartmini",insertOkFunction);
        }

    }).attr("href","javascript:void(0);");
}


