var baseUrl = '';
var filterParameters = new Array();
var filterParametersBackup = new Array();
var mageTranslations = new Hash();	//keep translation
var HasToTranslate = true; //send with params to set the PHP traduced Flag
var defaultHashString;
var defaultH1String;
var current_hash;
var categoryId;
var ajaxLimit;
var ajaxIndex;
var sortFilterArray = new Array();
var noLoading;
var categName = '';
var storeTitle = '';

//init
filterParameters.clear();

window.onload = function() {
    // ajoute le nom de la catégorie, optionnel, c'est pour éviter d'avoir un hash vide
    if(window.location.hash.replace(/^#/, '') == ''
        || window.location.hash.replace(/^#/, '') == defaultHashString) {
        if(filterParameters.length == 0) {
            window.location.hash = defaultHashString;
            // only the first time
            noLoading = true;
        } else {
            setHash();
        }
    }
    // mémorise le hash actuel
    current_hash = window.location.hash;
    getParameters();
    initHash();
}


function initFilter(FilterTrad, refresh){
    if(refresh == null)
    {
        refresh = false;
    }

    filterParameters.each(function (filter){
        if(filter[0] == escapeString(FilterTrad))
        {
            filter[1] = [];
        }
    });

    if(refresh)
    {
        setHash();
    }
}

var TYPE_ALL = 'all';
var TYPE_TYPE = 'product_type';
var TYPE_THEME = 'product_theme';
var TYPE_SILHOUETTE = 'product_silhouette';
var TYPE_COLOR = 'product_color';

function uncheckAllFilters(type)
{
    if(type != TYPE_ALL && type != TYPE_TYPE && type != TYPE_THEME && type != TYPE_COLOR && type != TYPE_SILHOUETTE) {
            type = TYPE_ALL;
        }

    allFiltersId.each(function (el) {
        if((el.value == TYPE_TYPE || el.value == TYPE_THEME)
             && (el.value == type || type == TYPE_ALL)){
            checkBoxSelected(el.key, UNCHECK_ONLY);
        }
        if(el.value == TYPE_SILHOUETTE
             && (el.value == type || type == TYPE_ALL)){
            checkSilhouette(el.key, UNCHECK_ONLY);
        }
        if(el.value == TYPE_COLOR
             && (el.value == type || type == TYPE_ALL)){
            checkColor(el.key, UNCHECK_ONLY);
        }

    });
}

function initFilters(){
    //uncheck checked filters
    //uncheckAllFilters();

    filterParameters = new Array();
    setHash();
}

function setPageParameter(type, value, traduction)
{
    mageTranslations.set(traduction, type);
    mageTranslations.set(value, value);
    var replaced = false;
    filterParameters.each(function (filter){
        if(filter[0] == traduction) {
            filter[1] = [value];
            replaced = true;
        }
    });
    if (!replaced) {
        filterParameters.push([traduction, [value]]);
    }
    // trie les parametres  pour faire joli
    orderFilters();
    // modifie le hash en consequence
    setHash();
}

//context setters
function addTranslation (valueCode, translation)
{
    mageTranslations.set(translation, valueCode);
}

function setCategoryId(catId)
{
    categoryId = catId;
}

function setCategoryName(catName)
{
    categName = catName;
}

function setStoreTitle(title)
{
    storeTitle = title;
}

function setDefaultHash(str)
{
    defaultHashString = str;
}

function setDefaultH1(str)
{
    defaultH1String = str;
}

function setBaseUrl(url)
{
    baseUrl = url;
}

function setSortArray(sortArray)
{
    sortFilterArray = sortArray;
}

//begin process
function initHash() {
    current_hash = document.location.hash;
    if(document.all) {
        // ajoute une iframe pour mémoriser le hash de IE
        document.body.innerHTML += '<iframe id="nav_history" style="display:none;"></iframe>';
        var ihistory = $("nav_history");
        var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
        iframe.open();
        iframe.close();
        iframe.location.hash = current_hash;
    }
    checkHashChange();
}

function checkHashChange() {
    // vérifie le hash
    if (document.all) {
        var ihistory = $("nav_history");
        var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
        if (current_hash != iframe.location.hash) {
            current_hash = iframe.location.hash;
            window.location.hash = current_hash;
            getParameters();
        }
    } else if (window.location.hash != current_hash) {
        current_hash = window.location.hash;

        getParameters();
    }
    setTimeout("checkHashChange()",100);
}

function getParameters() {
    filterParameters.clear();
    // construit le tableau de paramètres pour la page en cours
    if (current_hash.replace(/^#/, '') != '' && current_hash.replace(/^#/, '') != defaultHashString) {
        // découpe le hash en types et valeurs
        var hashTypes = current_hash.split('/');
        hashTypes.each(function (hashPart)
        {
            if(hashPart != '#' && hashPart != '') {
                // Take care of multiple sharp in subHash, only the first should be consider
                var firstDashIndex = hashPart.indexOf('-');
                //Extract filter Name
                var type_name = hashPart.substring(0, firstDashIndex);
                // HACK for the first filter Name
                if (type_name.charAt(0) == '#'){
                    type_name = type_name.substring(1, type_name.length);
                }
                // Extract values for filter name
                var type_values = hashPart.substring(firstDashIndex+1, hashPart.length).split('_');
                filterParameters.push([type_name, type_values]);


            }
        });
    } else {
        filterParameters = new Array();
    }
    // met à jour la page grâce aux paramètres
    performHash();
}

/**
 *
 * Add/delete a filter for ajax
 *
 * @param : String type,		name of the filter
 * @param : String value, 		value of the filter
 * @param : String mageType, 	code of the filter in magento
 * @param : String mageValue, 	value of the filter in magento
 *
 *	@return null;
 */
function setFilterParameter(type,value, mageType, mageValue) {
    initFilter('page');
    HasToTranslate = false;	//if set by javascript, no need to set the PHP translation flag
    mageTranslations.set(escapeString(type),  mageType);
    mageTranslations.set(escapeString(value), mageValue);
    // ajoute ou enleve le paramètre
    var type_values = new Array();
    var hasType = false;
    var tempFilter = new Array();

     //find indexOf this type
    var wanted = filterParameters.find(function (filter) {
        // ARRAY : [0] => filter name, [1] => filter value(s), [2] => mage filter name, [3] => mage filter value (s)
        if(filter[0] == escapeString(type))
            return true;
        return false;
    });
    
    var collection = filterParameters.find(function (filter) {
        if(filter[0] == escapeString('collection'))
            return true;
        return false;
    });
    var indexCollection = filterParameters.indexOf(collection);
    if (indexCollection != -1) {
        filterParameters[indexCollection][1].splice(0,filterParameters[indexCollection][1].length);
    }
    
    var index = filterParameters.indexOf(wanted);
    type_values = new Array();
    //if type was found
    if (index != -1) {
        var isExisting = false;
        filterParameters[index][1].each(function (existingValue, key){
            if(escapeString(value, true) == existingValue){
                filterParameters[index][1].splice(key, 1);
                if(filterParameters[index][1].size() <= 0)
                    filterParameters[index][1]= null;
                isExisting = true;
            }
        });
        if(!isExisting) {
            if (filterParameters[index][0] == 'produits') {
                filterParameters.each(function (eachFilter, key) {
                    if (key != index) {
                        filterParameters[key][1].splice(0,filterParameters[key][1].length);
                    }
                });
            }
            filterParameters[index][1].splice(0,filterParameters[index][1].length);
            filterParameters[index][1].push(value);
        }
    } else {
        type_values.push(value);
        filterParameters.push([type, type_values, mageType, mageValue]);
    }

    // trie les paramètres
    orderFilters();
    // modifie le hash en conséquence
    setHash();
}

function orderFilters()
{
    var tempFilters = new Array();
    //ordered by sortFilterArray
    sortFilterArray.each(function(element)
    {
        //we search for this filters
        filterParameters.each(function(filter)
        {
            if(findMagentoTraduction(filter[0]) == element)
            tempFilters.push(filter);
        });
    });
    //and resort its
    filterParameters = tempFilters;
}

//*/
function setHash() {
    var new_hash = '';
    filterParameters.each(function (filter) {
        if(filter[0].valueOf() != '' && filter[1]) {
            // ARRAY : [0] => filter name, [1] => filter value(s)
            var filterValues = '';
            filter[1].each(function (element) {
                filterValues += escapeString(element, true) + '_';
            });
            filterValues = filterValues.substr(0, filterValues.length-1);

            if(filter[0].valueOf() != '' && filterValues != ''){
                new_hash += escapeString(filter[0].valueOf()) + '-' + filterValues + "/";
            }
        }
    });

    // HACK for empty Hash
    if(new_hash == ''){
        new_hash = defaultHashString;
    }

    // modifie le hash
    if (document.all && $("nav_history") != null) {
        var ihistory = $("nav_history");
        var iframe = ihistory.contentWindow.document;
        iframe.open();
        iframe.close();
        iframe.location.hash = new_hash;
    }
    window.location.hash = new_hash;
    if (current_hash != '')
        current_hash = '/#'+new_hash;
}

function findMagentoTraduction(strToTranslate, isFilterValue)
{
    //si entier pas de translation
   if (parseInt(strToTranslate).toString() == strToTranslate)
    {
        return strToTranslate;
    }
    return mageTranslations.get(escapeString(strToTranslate, isFilterValue));
}


var currentRequest;

function performHash() {
    // construit les parametres pour l'Ajax a partir du tableau de parametres
    //prepare post params hash
    var postParams = '';
    var newFilterParameters = new Array();
    filterParameters.each(function (filter) {
        if(filter[0].valueOf() != '') {
            newFilterParameters.push(filter);
            // ARRAY : [0] => filter name, [1] => filter value(s)
            var filterValues = '';
            filter[1].each(function (element) {
               if(!HasToTranslate) {
                    filterValues += findMagentoTraduction(element, true) + '_';
               } else  {
                   filterValues += element.replace('&', '%26') + '_';
               }
            });
            filterValues = filterValues.substr(0, filterValues.length-1);
            if(!HasToTranslate)
            {
                FilterName = findMagentoTraduction(filter[0]);
            }
            else
            {
                FilterName = filter[0].valueOf().replace('&', '%26');
            }
            if(FilterName != '' && filterValues != ''){
                postParams += FilterName + '=' + filterValues + "&";
            }
        }
    });

    var url = baseUrl + "ajaxcatalog/category";
    
    if(postParams == '') {
            //no need to translate if there is no data
            HasToTranslate = false;
    }
    postParams += 'categoryId=' + categoryId + 
                  '&hasToTranslate=' + HasToTranslate + 
                  // en GET le # ne passe pas, du coup il faut le remplacer par un pipe, et le remodifier à la réception par le PHP
                  '&categoryurl=' + window.location.pathname + '|' + window.location.hash.replace('#', '');
        
    filterParameters = newFilterParameters;
    
     if (noLoading) {
         // now load all
         noLoading = false;
    } else {
        //******************************//
        //*** LANCER LA  REQUETE ***//
        //******************************//
        new Ajax.Request(url, {
            method: 'get',
            parameters: postParams,
            onLoading: function(xhr) {
                currentRequest = postParams;
                //*******************************//
                //** LANCER LE CHARGEMENT **//
                //*******************************//
                var xWidth = $('category-products').offsetWidth;
                var yHeight = $('category-products').offsetHeight;
                if ($('product_mask') == null) {
                    $('category-products').innerHTML = '<div id="product_mask" style="height:'+yHeight+'px; width:'+xWidth+'px;"></div><div id="product_loader"></div><div id="loader_text">Chargement</div>'+$('category-products').innerHTML;
                }
            },
            onSuccess: function(xhr) {
                // verifie que l'on ait pas lancé une autre requete entre-temps
                if (postParams == currentRequest) {
                    if(current_hash != '#' + defaultHashString){
                        var googleAnalyticUrl = window.location.pathname + '/' + window.location.hash.replace('#', '')
                        pageTracker._trackPageview(googleAnalyticUrl);
                    } else {
                        pageTracker._trackPageview(window.location.pathname);
                    }

                    //update main product list block
                    if($('category-products')) {
                        $('category-products').innerHTML = xhr.responseText;
                        
                        // change H1 et footer
                        $('category-title').innerHTML = $('backup_h1').innerHTML;
                        $('footer_description').innerHTML = $('backup_footer').innerHTML;
                        document.title = $('backup_title').innerHTML;
                    }

                    if (filterParameters.length > 0) {
                        $('gondole').setStyle({ display: 'none' });
                    } else {
                        $('gondole').setStyle({ display: 'block' });
                    }
                }
            }
        });
    }
    
    selectFilters(filterParameters);
}

/**
 * Strip accentuation from a string and return it in lower case
 *
 * @param string str to be escaped
 * @return string escaped
 */
function escapeString(str, isFilterValue) {
      temp = str.toLowerCase();
      temp = temp.replace(/[àáâãäÀÁÂÃÄ]/g,"a");
      temp = temp.replace(/[çÇ]/g,"c");
      temp = temp.replace(/[èéêëÈÉÊË]/g,"e");
      temp = temp.replace(/[ìíîïÌÍÎÏ]/g,"i");
      temp = temp.replace(/[òóôõöÒÓÔÕÖ]/g,"o");
      temp = temp.replace(/[ùúûüÙÚÛÜ]/g,"u");
      temp = temp.replace(/[ñÑ]/g,"n");
      temp = temp.replace(/[ýÿÝ]/g,"y");
      temp = temp.replace(/[œ]/g,"oe");
      temp = temp.replace(/[^a-zA-Z0-9 -_&]/g,"");
      temp = temp.replace(/ /g,"-");
      temp = temp.replace(/^-*/g,"");
      temp = temp.replace(/-*$/g,"");
      temp = temp.replace(/-+/g,"-");
      if(!isFilterValue)
      {
          temp = temp.replace(/-/g, "_");
      }
      else
      {
          temp = temp.replace(/_/g, "-");
      }

      return temp;
}
