/**
 * 
 */
function parseAmazonResponse(data){
    var result = {totalResults:0, totalPages: 0, items: []};
    
    $(data).find("Items").each(function(index, el){        
        var children = $(el).children();
        
        children.each(function(){
            var child = $(this);            
            var nodeName = this.nodeName;
            
            if(nodeName == "TotalResults"){                
                result.totalResults = parseInt(child.text());                
            }else if(nodeName == "TotalPages"){
                result.totalPages = parseInt(child.text());
            }else if(nodeName == "Item"){               
                var asin;
                var pic;
                var listPrice;
                var priceNew;
                var priceUsed;
                var editorialReview;
                
                child.children().each(function(){
                    var property = $(this);
                    var itemNodeName = this.nodeName;                    
                    
                    if(itemNodeName == "ASIN"){                       
                        asin = property.text();                        
                    }else if(itemNodeName == "SmallImage"){
                        pic = {
                            'url'   : $(property.children()[0]).text(),
                            'heigh' : parseInt($(property.children()[1]).text()),
                            'width' : parseInt($(property.children()[2]).text()),
                        };                        
                    }else if(itemNodeName == "ItemAttributes"){
                        listPrice = $($($(property).children("ListPrice")[0]).children()[2]).text();                        
                    }else if(itemNodeName == "OfferSummary"){
                        priceNew = $($(property.children()[0]).children()[2]).text();
                        priceUsed = $($(property.children()[1]).children()[2]).text();                        
                    }else if(itemNodeName == "EditorialReviews"){                       
                        editorialReview = $($(property.children()[0]).children()[1]).text();                        
                    }
                });
                
                if(!pic){
                    src = "/images/amazon_na.gif";                    
                }else{
                    src = pic.url;                    
                }
                
                result.items.push({
                    asin: asin,
                    pic: src,
                    listPrice: listPrice,
                    priceNew: priceNew,
                    priceUsed: priceUsed,
                    editorialReview: editorialReview
                });
            }
        });
        
    });
    
    return result;
}

function displayAmazonProducts(){   
    var languageMap = FOD.languageMap;
    
    var amazonItems = $("div.amazonItem");
    $(amazonItems).each(function(){$(this).fadeOut();});
    $("div.tooltip").remove();
    $.ajax({
        url         : "/amazon",
        data        : {
            "l1" :  languageMap[ $("#ol :selected").val() ],
            "l2" : "english"
        },
        dataType    : "xml",
        error       : function(xhr, status, e){console.log("error", status, e);},
        success     : function(data, status, xhr){            
            var result = parseAmazonResponse(data); 
           
            for(var i = 0; i < amazonItems.length && i < result.items.length; i++){
                var item = result.items[i];
                                
                var asin = item.asin;
                var pic = item.pic;
                var listPrice = item.listPrice;
                var priceNew = item.priceNew;
                var priceUsed = item.priceUsed;
                var editorialReview = item.editorialReview;
                
                var img = document.createElement("img");
                img.setAttribute("src", pic);
                img.setAttribute("class", "amazonItem"); 
                
                var a = document.createElement("a");
                a.setAttribute("class", "amazonItem");
                var href = document.location.protocol + '//astore.amazon.com/freeop-20/detail/' + asin;
                a.setAttribute("href", href);
                a.setAttribute("target", "_blank");
                if(editorialReview){
                    a.setAttribute("title", '<cite>"' + editorialReview.substr(0, 255) + ' ... "</cite>'
                            + '<div style="color:red">Limited offer!</div>'
                            + '<div style="margin:10px 0px;">Interested? <a style="color:red;" href="' + href + '" target="_blank">Click now!</a></div>'
                    );
                    
                    $(a).tooltip({                    
                        // tweak the position
                        offset: [10, 2],                  
                        // use the "slide" effect
                        effect: 'slide'                  
                     // add dynamic plugin with optional configuration for bottom edge
                    }).dynamic({ bottom: { direction: 'down', bounce: true } });
                }
                a.appendChild(img);
                                
                $(amazonItems[i]).empty().append(a).fadeIn();
            };
        }
    });
}

$(document).ready(displayAmazonProducts);
$(document).ready(function(){
    $("#ol").change(displayAmazonProducts);
});
