﻿//////////////////////////////////////////////
//  Les sélections Bordeaux Abordables
//////////////////////////////////////////////
function initPage() {
    // build XML objects
	categories = xmlCat.getElementsByTagName('criteres');
    vins =  xmlVin.getElementsByTagName('vins');
    
	
	//if(vins[0]) alert('vins: Valid');
	//if(categories[0]) alert('categories: Valid');

    // Get variables from c# code
    getCVars();

	searchBox.value = searchLabel;
    setTimeout("buildImagesArray();" , 50);
    setTimeout("getWineListCookies();" , 50);
}

////////////////////////////////////////////
/////////// Custom Drop down Lists
////////////////////////////////////////////
function catSelect(div,box,Cat,Sub,SubSub) {
    // Deselect other options and select <div>
    catDeSelectSiblings(div);
    div.className = "selectedOption";
    rollover(div,1);

    // reset the search box and following option lists
    searchBox.value=searchLabel;
    switch (box) {
        case 1: 
            SubSub=0;
            Sub=0;
            break;
        
        case 2:
            SubSub=0;
            break;
    }
    
    // Fill up the categories
    switch (box) {
        case 1: 
            fillCat(2,Cat,Sub,SubSub);
            fillCat(3,Cat,Sub,SubSub);
            break;
        
        case 2:
            fillCat(3,Cat,Sub,SubSub);
            break;
    }
    
    // Update cookies and wine list
    updateWineListCookies(Cat,Sub,SubSub);
    updateWineList(Cat,Sub,SubSub);
}

function catDeSelectSiblings(which){
    // Deselect all siblings in <which> option list
    siblings = which.parentNode.childNodes.length;
    for (i=0; i < siblings; i++) {
	    div = which.parentNode.childNodes[i];
	    div.className = (i%2 != 0) ? "unselectedOption" : "unselectedOptionAlt";
	    rollover(div, 0);
    } 
}

function rollover(div,state) {
    bg = rolloverBG;
    switch (div.className) {
        case "unselectedOption":
	        if(!state) { bg = unselectedBG; }
	        break;
	        
        case "unselectedOptionAlt":
	        if(!state) { bg = unselectedBGAlt; }
	        break;

        case "wineList":
	        if(!state) { bg = unselectedBG; }
	        break;
	        
        case "wineListAlt":
	        if(!state) { bg = unselectedBGAlt; }
	        break;
	        
        case "selectedOption":
            bg = selectedBG;
            break;
    }
    div.style.backgroundColor = bg;
}

////////////////////////////////////////////
/////////// Filtres
////////////////////////////////////////////
function fillCat(box, Cat, Sub, SubSub) {
    // Fill option list <box>
    switch(box) {
        case 1:
            node = categories[0].childNodes;
            break;
        case 2:
            node = categories[0].childNodes[Cat].childNodes;
            break;
        case 3:
            node = categories[0].childNodes[Cat].childNodes[Sub].childNodes;
            break;
    }
    document.getElementById('catBox'+box).innerHTML = buildDiv(box, Cat, Sub, SubSub, node);
    document.getElementById('catBox'+box).scrollTop = 0;
}

function buildDiv(box, Cat, Sub, SubSub, node) {
    // Build the option list html
	
	//alert("box:" +box+" Cat:" + Cat + " Sub:" + Sub + " SubSub:" + SubSub);
    str="";
    j=0;
    sCat = Cat;
    sSub = Sub;
    sSubSub = SubSub;

	for (i=0; i<node.length; i++) {
        if(node[i].nodeType == 1) {
            sel = "unselectedOption";

			switch (box) {
                case 1: 
                    if (sCat == j) { sel = "selectedOption"; }
                    Cat = i;
                    break;
                    
                case 2: 
                    if (sSub == j) { sel = "selectedOption"; }
                    Sub = i;
                    break;
                
                case 3: 
                    if (sSubSub == j) { sel = "selectedOption"; }
                    SubSub = i;
                    break;
            }
            
            if (sel != "selectedOption" && j % 2 == 0) { sel = "unselectedOptionAlt"; }
            j++;
            str+="<div class='"+sel+"' id='' onmouseover='rollover(this,1)' onmouseout='rollover(this,0)'";
            str+="onclick='catSelect(this," + box + "," + Cat + "," + Sub +"," + SubSub + ")'>";
            str+=getXML(node[i],"title");
            str+="</div>";
        }
    }
	return str;
}

function goToDetails(codeVin) {
    // Go to wine details page
    document.location.href='vins.aspx?Code=' + codeVin + '&culture=' + pageParams;
}

////////////////////////////////////////////
/////////// Wine List / Filtres
////////////////////////////////////////////
function updateWineList(Cat,Sub,SubSub) {
    // Update the wine list
    node = vins;
    displayedWines = new Array();
    // Get the required information from the categories XML according to selected <Cat> if a Sub is selected
    if (Sub != 0) {
        switch (Cat) {
            // All Wines
            case 0:
                typeCouleur = getXML(categories[0].childNodes[Cat].childNodes[Sub],"id");
                break;
            
            // Appellations            
            case 1:
                srchSubSub = getXML(categories[0].childNodes[Cat].childNodes[Sub].childNodes[SubSub], "title");
                srchSub = getXML(categories[0].childNodes[Cat].childNodes[Sub], "title");
                break;

            // Occasions
            case 2:
                occ = getXML(categories[0].childNodes[Cat].childNodes[Sub],"title");
                break;

            // Food & Wine Combo
            case 3:
                fNode = (SubSub == 0) ? categories[0].childNodes[Cat].childNodes[Sub] : categories[0].childNodes[Cat].childNodes[Sub].childNodes[SubSub];
                met = getXML(fNode,"id");
                fNode = fNode.parentNode;
			break;
        }
    }
    
    // Go through each wine in Wine XML
    for (i=0; i<node[0].childNodes.length; i++) {
        // All wines : no filtering
        if(Sub == 0) {
            displayedWines.push(i);
        }
        
        // Filtre by Types/Color
        if(Cat == 0 && Sub != 0) {
            if(typeCouleur == getXML(node[0].childNodes[i],"couleur")) displayedWines.push(i);
        }

        // Filtre by appellations
        if(Cat == 1 && Sub != 0) {
            if(SubSub != 0) {
                // Filtrer par appellation
                if(srchSubSub == getXML(node[0].childNodes[i],"appellation") && srchSub == getXML(node[0].childNodes[i],"famille")) displayedWines.push(i);
            } else {
                // Filtrer par Familles d'Appellations
                if(srchSub == getXML(node[0].childNodes[i],"famille")) displayedWines.push(i);
            }
        }
        
        // Filtre by Occasion
        if(Cat == 2 && Sub != 0) {
            a = getXML(node[0].childNodes[i],"occasions").split(";");
            for(j=0; j < a.length; j++) {
                if(a[j] == occ) {
                    displayedWines.push(i);
                }
            }
        }

        // Filtre by meal / meal type
        if(Cat == 3 && Sub != 0) {
			a = (SubSub == 0) ? getXML(node[0].childNodes[i],"familleMets").split(";") : getXML(node[0].childNodes[i],"mets").split(";");
            for(j=0; j < a.length; j++) {
                if(a[j] == met) {
                    displayedWines.push(i);
                }
            }
        }
    }

    // sort results according to selected sort method (radio button)
    displayedWines = sortArray(displayedWines);    
    buildList(displayedWines,"");
}

function sortArray(which) {
    // Sort array alphabeticly by <which> attribute
    tmpArray = new Array();
    for (i=0; i < which.length; i++) {
        tmpArray[i]= vins[0].childNodes[which[i]].getAttributeNode(radioSort).nodeValue + "&&" + which[i];
    }
    tmpArray.sort();
    for (i=0; i < tmpArray.length; i++) {
        li = tmpArray[i].lastIndexOf("&&");
        v = tmpArray[i];
        v = v.substring(li+2,999);
        which[i]=v;
    }
    return which;
}

function buildList(displayedWines, searchText) {
    // Rebuild the wine list
    str="";
    node = vins[0].childNodes;
            
    // Go through all filtered wines

    for (i=0; i < displayedWines.length; i++) {
        // Retrieve the wines attributes
        ind = displayedWines[i];
        description = getXML(node[ind],"title");
        if(getXML(node[ind],"millesime").length > 0) { description += ", " +  getXML(node[ind],"millesime"); }
        vigneron = getXML(node[ind],"appellation")+ ", ";
        famille = getXML(node[ind],"famille");
        imageFileName = getXML(node[ind],"imageE");
        codeVin = getXML(node[ind],"id");
        cls = (i%2) ? "wineList":"wineListAlt";

        //Highlite the searched text
        if(searchText != "") {
            description = highLite(description,searchText);
            vigneron = highLite(vigneron,searchText);
            famille = highLite(famille,searchText);
        }
        imagePath="../tout-vins/data/images/e/";
        if(imageFileName == "PasDispo_e.gif") {
            imagePath="../tout-vins/images/" + culture + "/";
        }
        

        // Build this wine's div
        str+="<div class='" + cls + "' id='' onmouseover='rollover(this, 1)' onmouseout='rollover(this,0)' onclick='goToDetails(\""+ codeVin + "\");'>";
        str+="<img src='" + imagePath + imageFileName + "' name='img"+displayedWines[i] +"' width=93 height=49 alt='' border='0' class='wineImage' onError='this.src = \"../images/" + culture +"/PasDispo_e.jpg\"' />";
        str+="<img src='../Images/coupe" + couleursArr[node[ind].getAttributeNode("couleur").nodeValue] + ".gif' width='19' height='26' alt='' border='0' class='colorImage' />";
        str+="<div class='wineText'><strong>";
        str+=description;
        str+="</strong><div style='padding-top: 8px;'>";
        str+=vigneron;
        str+=famille;
        str+="</div>";
        str+="</div>";
        str+="</div><div style='clear:both'></div>";
    }
    
    // If no wines available display error message
    if (displayedWines.length < 1) {
        str='<div style="padding:10px;">' + msgNoResult + '</div>';
    }
    
    // Display the results
    document.getElementById("results").innerHTML = "<div style='padding-top:3px;'>" + displayedWines.length + " " + displayedLabel + "</div>";
    document.getElementById("Output").innerHTML = str;
}

function highLite(Txt,Searched) {
    // Highlights <Searched> in <Txt>
    s = new RegExp(Searched,"gi");
    d = removeAccents(Txt);
    indexes= d.search(s);

    if(indexes >=0) {
        p1=Txt.substr(0, indexes);
        p2=Txt.substr(indexes, Searched.length).highlighted();
        p3=Txt.substr(indexes + Searched.length, 9999);
        Txt =  p1 + p2 + p3;
    }
    return Txt;
}

String.prototype.highlighted = function (){
    return "<span style='color: red; font-weight:bold;'>" + this + "</span>";
}    

function clearFilters() {
    // Reset the filtres
    Cat = 0;
    Sub = 0;
    SubSub = 0;
    fillCat(1,0,0,0);
    fillCat(2,0,0,0);
    fillCat(3,0,0,0);
}

////////////////////////////////////////////
/////////// Radio Buttons
////////////////////////////////////////////
function updateRadioSort(which) {
    //Update the radio button sorting value
    getWineListCookies();
    radioSort = which;
    checkRadioButton();
    
    document.cookie = "WineListRadioSort=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = "WineListRadioSort="+radioSort+"; path=/ ";
    
    // Update wine list from either search box or filtres
    if(searchBox.value == searchLabel) {
        updateWineList(Cat,Sub,SubSub);
    } else {
        searchUpdate(searchBox.value)
    }
}

function checkRadioButton() {
    // Check the correct radio button
    switch (radioSort) {
        case 'couleur':
            document.forms[0].tri[0].checked = true;
            break;
        case 'title':
            document.forms[0].tri[1].checked = true;
            break;
        case 'famille':
            document.forms[0].tri[2].checked = true;
            break;
    }
}

////////////////////////////////////////////
/////////// Cookies
////////////////////////////////////////////
function getCookie(cookie_name) {
    var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
    if(results) {    
        return (unescape(results[1]));
    } else {
        return 0;
    }
}

function updateWineListCookies(Cat,Sub,SubSub){
    var regExpAlphaNum = /\w/;
    // expression réguliere pour charateres alpha numerique
    deleteWineListCookies();
    document.cookie = "WineListCat="+Cat+"; path=/ ";
    document.cookie = "WineListSub="+Sub+"; path=/ ";
    document.cookie = "WineListSubSub="+SubSub+"; path=/ ";
    document.cookie = "WineListRadioSort="+radioSort+"; path=/ ";
     if( searchBox.value.match( regExpAlphaNum ) ) {
        document.cookie = "WineListSearchTxt="+searchBox.value+"; path=/ ";
     }
}

function getWineListCookies() {
    if(getCookie("WineListRadioSort") != 0){
        Cat = getCookie("WineListCat");
        Sub = getCookie("WineListSub");
        SubSub = getCookie("WineListSubSub");
        radioSort = getCookie("WineListRadioSort");
        searchBox.value = getCookie("WineListSearchTxt");
    }
    
    
    for(i=0; i < emptySearchValues.length; i++) {
        if(emptySearchValues[i] == searchBox.value) {
            searchBox.value = searchLabel;        
        }
    }

    if(radioSort == 0) { radioSort = 'title'; }
    
    checkRadioButton();

    setTimeout("fillCat(1," + Cat + "," + Sub + "," + SubSub + ");", 100);
    setTimeout("fillCat(2," + Cat + "," + Sub + "," + SubSub + ");", 100);
    setTimeout("fillCat(3," + Cat + "," + Sub + "," + SubSub + ");", 100);
    
    if(searchBox.value == searchLabel) {
        setTimeout("updateWineList(" + Cat + "," + Sub + "," + SubSub + ");", 100);
    } else {
        searchUpdate(searchBox.value);
    }        
}

function deleteWineListCookies() {
    document.cookie = "WineListCat=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = "WineListSub=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = "WineListSubSub=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = "WineListRadioSort=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
    document.cookie = "WineListSearchTxt=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

////////////////////////////////////////////
/////////// SearchBox
////////////////////////////////////////////
function searchUpdate(searchText) {
    if(searchText!="" && searchText!="0" ){
        clearFilters();
        updateWineListCookies(0,0,0);
        
        // Build the array
        displayedWines = new Array();
        
        searchText = removeAccents(searchText);
        rExp = new RegExp(searchText,"gi");
        
        for (i=0; i < vins[0].childNodes.length; i++) {
            str1 = getXML(vins[0].childNodes[i],"title");
            if(getXML(vins[0].childNodes[i],"millesime").length > 0) { str1 += ", " +  getXML(vins[0].childNodes[i],"millesime"); }
            str1 = removeAccents(str1);
            str2 = removeAccents(getXML(vins[0].childNodes[i],"appellation"));
            str3 = removeAccents(getXML(vins[0].childNodes[i],"famille"));
            srch1 = str1.search(rExp);
            srch2 = str2.search(rExp);
            srch3 = str3.search(rExp);
            if(srch1 >= 0 || srch2 >= 0 || srch3 >= 0 ) {
                displayedWines.push(i);
            }
        }
        
        displayedWines = sortArray(displayedWines);    
        buildList(displayedWines,searchText);
    } else {
        searchText.value=searchLabel;
        updateWineListCookies(0,0,0);
        updateWineList(0,0,0);
    }
}


function clearSearch() {
    // Reset search box
    if (searchBox.value== searchLabel)
        searchBox.value = "";
} 

function buildImagesArray() {
    // Preload images
    t= new Image(93,49);

    for (i=0; i < vins[0].childNodes.length; i++) {
        image = getXML(vins[0].childNodes[i],"imageE");
        if(image != "PasDispo_e.jpg") {
            t.src='../tout-vins/data/images/' + image;
        }
        imgArray.push(t.src);
    }
}

////////////////////////////////////////////
/////////// Misc
////////////////////////////////////////////
function getXML(node, prop) {
    // Get an xml node attribute's value if it exists
    if(node){
        if(node.nodeType == 1) {
            return node.getAttributeNode(prop).nodeValue;
        }
    } else { alert(node + "||" + prop); }
}

function removeAccents(str) {
    str = str.replace(/À|Á|Â|Ã|Ä|Å|à|á|â|ã|ä|å/g,"a");
    str = str.replace(/Ò|Ó|Ô|Õ|Ö|Ø|ò|ó|ô|õ|ö|ø/g,"o");
    str = str.replace(/È|É|Ê|Ë|è|é|ê|ë/g,"e");
    str = str.replace(/Ç|ç/g,"c");
    str = str.replace(/Ì|Í|Î|Ï|ì|í|î|ï/g,"i");
    str = str.replace(/Ù|Ú|Û|Ü|ù|ú|û|ü/g,"u");
    str = str.replace(/ÿ/g,"y");
    str = str.replace(/Ñ|ñ/g,"n");
    return str;
}

function noWineForThisCountry() {
    // Display the error message and hide the wine list & filtres
    document.getElementById("txtSearchDiv").style.display = "none";
    document.getElementById('emptyList').style.display = "inline";
    document.getElementById('wineList').style.display = "none";
    document.getElementById('categories').style.display = "none";
}
