/* Firebug logging */
jQuery.fn.log = function (msg) {
  ////console.log("%s: %o", msg, this);
  return this;
};
var debugLoops = 0;
$(document).ready(function()
{
  var xmlDoc;
  var productXmlDoc;
  var productResultIds;
  var productResultData;
  
  start();
  
});
function prepareForInitialScreens() {
  // hide other containers
  $("#cpa-product-detail-view").hide();
  $("#cpa-product-feature-comparison-view").hide();
  $("#cpa-history-element").empty();
  
  // set up current container
  $("#decision-page").show();
  $("#decision-page").removeClass();
  $("#decision-page").addClass('product-chooser');
  
  // product screen button actions
  $("a.product-detail").unbind("click").click(function() { 
    $("#cpa-product-detail-view").show(); 
    $("#cpa-product-feature-comparison-view").hide();  
  });
  $("a.product-feature-comparison").unbind("click").click(function() { $("#cpa-product-detail-view").hide(); $("#cpa-product-feature-comparison-view").show(); });
}

function start() {
   prepareForInitialScreens();
   // load XML  
   $.ajax({
     type: "GET",
     url: localizationPath + "configuration.xml",
     dataType: "xml",
     success: parseConfigurationXml
   });

}
function selectProductGroup() {
   prepareForInitialScreens();
  
  // set up content
  //$("#cpa-history-element").append("<li><a href=\"#null\" id=\"my-requirements\">"+configurationXmlDoc.find("#historyElement-myRequirements").text()+"</a></li>");
  $("#my-requirements").unbind("click").click(selectProductGroup);
  $("#decision-page").html("<div id=\"select-product-group\" />");
  $("#select-product-group").append("<ul id=\"product-list\" />");
  $("#select-product-group").append("<div id=\"diagram\" />");
  $("#cpa-branding").html(configurationXmlDoc.find("#selectProductGroup-cpaBranding").text());

  
  
  // load XML  
  $.ajax({
    type: "GET",
    url: localizationPath + "decision-tree.xml",
    dataType: "xml",
    success: parseXml
  });

}
function parseConfigurationXml(xml)
{
  //populate top layer
  configurationXmlDoc = $(xml);
  
  // set up content
  $("#cpa-history-element").html("<li>&nbsp</li>");
  $("#cpa-branding").html(configurationXmlDoc.find("#welcome-cpaBranding").text());
  $("#decision-page").html("<div class=\"start-content\"><p>"+configurationXmlDoc.find("#welcome-startContent").text()+"</p><p><a href=\"#null\" id=\"start-now\">"+configurationXmlDoc.find("#welcome-startNow").text()+"</a></div>");
  
  // Click
  $("#start-now").unbind("click").click(selectProductGroup);
  
  $("#pagination-proposition").html(configurationXmlDoc.find("#productDetail-paginationProposition").text());
  $("#product-previous").html(configurationXmlDoc.find("#productDetail-productPrevious").text());
  $("#product-next").html(configurationXmlDoc.find("#productDetail-productNext").text());
  $(".view-products").html(configurationXmlDoc.find("#productDetail-viewProducts").text());
  $(".quick-compare").html(configurationXmlDoc.find("#productDetail-quickCompare").text());
  $("#buy-link").html(configurationXmlDoc.find("#productDetail-buyLink").text());
  $(".reseller-a").html(configurationXmlDoc.find("#productDetail-resellerA").text());
  $(".reseller-b").html(configurationXmlDoc.find("#productDetail-resellerB").text());
  $(".reseller-b").attr("href", configurationXmlDoc.find("#productDetail-resellerB").attr("href"));
  $(".reseller-c").html(configurationXmlDoc.find("#productDetail-resellerC").text());
  
  
  
}    
       
function parseXml(xml)
{
  //populate top layer
  xmlDoc = $(xml);
  // the images to be preloaded for the rollover effect
  var images = new Array();

  xmlDoc.find("decision-tree > option").each(function()
  {
    images.push(localizationPath + 'diagram-' + $(this).attr("id") + '.png');
    
    $("#product-list").append("<li><a href=\"#null\" id=\"" + $(this).attr("id") + "\" historyElement=\"" + $(this).attr("historyElement") + "\">" + $(this).attr("title") + "</a></li>");
    $("#" + $(this).attr("id")).unbind("click").click(function() {
         
         $("#cpa-advisor").attr("category", $(this).attr("id"));
         
         loadDecisionPage($(this).attr("id"));
         
         var historyElement = $(this).text();
         if($(this).attr("historyElement") != 'undefined') {
           historyElement = $(this).attr("historyElement");
         }
         
         updateHistoryElement($(this).attr("id"), historyElement);
       });
  });
  
  // the preload function
  (function($){
  	$.preloadImages = function(images){ 
  		for (var i = 0; i < images.length; i++) {
  	    $('<img>').attr('src', images[i]);
  	  }
  	}
  })(jQuery);
  
  // call the preload function
  $.preloadImages(images);
  
  // the rollover effect for screen 1
  $(function(){
  	$('ul#product-list li a').hover(
  		function(event) {
  			$('div#diagram').html('<img src="'+localizationPath+'diagram-'+event.target.id+'.png" alt="" />');
  		},
  		function(event) {
  			$('div#diagram').empty();
  		}
  	);
  });
}    
function parseProductXml(xml)
{
  //populate top layer
  productXmlDoc = $(xml);
  productResultData = new Array();
  
  var productTypeLable;
  
  
  var numResults = 0;
  productXmlDoc.find("products > product").each(function()
  {
     if(jQuery.inArray($(this).attr("sku"), productResultIds) != -1) {
       numResults++;
       productResultData.push($(this));
       
       if(numResults== 1) {
         productTypeLable = xmlDoc.find("#"+$("#cpa-advisor").attr("category")).attr("singular");
       } else {
         productTypeLable = xmlDoc.find("#"+$("#cpa-advisor").attr("category")).attr("plural");
       }
       
       $(".productType").html(productTypeLable);
     }
  });
  
  populateProductView(0);
  populateQuickCompareView();
}

function loadDecisionPage(id) {
  $("#cpa-product-detail-view").hide();
  $("#cpa-product-feature-comparison-view").hide();
  $("#cpa-history-element").show();
  $("#decision-page").show();
  $("#decision-page").empty();
  $("#cpa-branding").html(xmlDoc.find("#" + id + " > next-question").text());
  $("#decision-page").empty();
  var choiceCount = 0;
  
  // show product detail view
  if(xmlDoc.find("#" + id + " > results > result").size() > 0) {
    $("#decision-page").hide();
    $("#cpa-product-detail-view").show();

    $("#cpa-branding").html(configurationXmlDoc.find("#decisionPage-cpaBranding-a").text()+'&nbsp;<span class="numberOfResults" />&nbsp;<span class="productType" /> '+configurationXmlDoc.find("#decisionPage-cpaBranding-b").text());
    
    $(".numberOfResults").empty();
    
    productResultIds = new Array();
    xmlDoc.find("#" + id + " > results > result").each(function() {
      productResultIds.push($(this).attr("sku"));
    });
    
    $(".numberOfResults").html(xmlDoc.find("#" + id + " > results > result").size());
    $.ajax({
       type: "GET",
       url: localizationPath + "products.xml",
       dataType: "xml",
       success: parseProductXml
     });
  } else if(xmlDoc.find("#" + id + " > yes-no-description").size() > 0) {
    //yes-no question
    $("#decision-page").html('<div style="display: block;" id="decision-page" class="yes-no choices"><div class="explanation"><p class="description">'+xmlDoc.find("#" + id + " > yes-no-description").text()+'</p><div class="yes-no-buttons"></div></div></div>');
    
    var yesNoButtonsHTML = "";
    xmlDoc.find("#" + id + " > options > option").each(function() {
      $(".yes-no-buttons").append('<a href="#null" class="button ' + $(this).attr("title").toLowerCase() + '" id="' + $(this).attr("id") + '" title="' + $(this).attr("title") + '" historyElement="' + $(this).attr("historyElement") + '">' + $(this).attr("title") + '</a>');
      $("#" + $(this).attr("id")).unbind("click").click(function() {
          
          loadDecisionPage($(this).attr("id"));
          var historyElement = $(this).attr("title");
           if($(this).attr("historyElement") != 'undefined') {
             historyElement = $(this).attr("historyElement");
           }

           updateHistoryElement($(this).attr("id"), historyElement);
        });
    });
   
    $("#decision-page").removeClass();
    $("#decision-page").addClass('choices');
    $("#decision-page").addClass('yes-no');
  } else {
    //multiple choice
    xmlDoc.find("#" + id + " > options > option").each(function() {
      choiceCount++;
      $("#decision-page").append('<div class="choice" id="choice-'+ $(this).attr("id") + '">' + 
      '<div class="choice-intro">' +
      '<h2>'+$(this).attr("title") +"</h2>" +
      '<p class="description">'+xmlDoc.find("#" + $(this).attr("id")  + " > description > p").text()+'</p>' +
      '</div>' +
      '<a href="#null" class="button" id="' + $(this).attr("id") + '" title=\"' + $(this).attr("title") + '\" historyElement=\"' + $(this).attr("historyElement") + '\">Select</a>' +
      '<ul class="list-items"></ul>' +
      '</div>');
    
      var currentChoiceId = $(this).attr("id");
      xmlDoc.find("#" + $(this).attr("id") + " > description > ul > li").each(function() {
        $('#choice-'+ currentChoiceId + ' > ul').append('<li>'+$(this).text()+'</li>');
      }); 
      $("#" + $(this).attr("id")).unbind("click").click(function() {
          loadDecisionPage($(this).attr("id"));
          var historyElement = $(this).attr("title");
           if($(this).attr("historyElement") != 'undefined') {
             historyElement = $(this).attr("historyElement");
           }
         
           updateHistoryElement($(this).attr("id"), historyElement);
        });
    });
    $("#decision-page").removeClass();
    $("#decision-page").addClass('choices');
    $("#decision-page").addClass('choices-'+choiceCount);
    $("#decision-page > .choice:last").addClass('last');
  }
}

function populateProductView(step) {
  
  ////console.log(debugLoops++ +'-1');
  if(step >= productResultData.size || step < 0) {
    step=0;
  }
  var currentProduct = new Array();
  currentProduct = productResultData[step];
  ////console.log('2');
  if(currentProduct != undefined) {
    $(".product-name").html('<a href="'+currentProduct.find("product-page-url").text()+'" target="_blank">'+currentProduct.find("product-name").text()+'</a>');
    $(".product-description").html(currentProduct.find("product-description").text());
    $(".product-bullets").empty();
    currentProduct.find("bullets > bullet").each(function() {
      $(".product-bullets").append('<li>'+$(this).text()+'</li>');
    });
    $("#cpa-product-image").html('<img src="'+currentProduct.find("product-image-url").text()+'" />');
    $("#buy-link").attr("href",currentProduct.find("buy-url").text());
    $("#buy-link").attr("target","_blank");
    
    
    // disable pagination at end points
    if(step==0) {
      //first step
      $("#product-previous").addClass('disabled');
      $("#product-previous").unbind("click");
    } else {
      $("#product-previous").removeClass('disabled');
      $("#product-previous").unbind("click").click(function() { populateProductView(step-1); });
    }
    
    if((step+1)==productResultData.length) {
      $("#product-next").addClass('disabled');
      $("#product-next").unbind("click");
    } else {
      $("#product-next").removeClass('disabled');
      $("#product-next").unbind("click").click(function() { populateProductView(step+1); });
    }

    $(".currentResult").empty();
    $(".currentResult").html(step+1);
    $("#cpa-product-feature-comparison-view").hide();
    $("#cpa-product-detail-view").show(); 
    
  }
}
function populateQuickCompareView() {
  var attributeColumns = new Array();
  
  for (var i = 0; i < productResultData.length; i++) {
    // Attributes
    productResultData[i].find('attribute').each(function() {
      if(jQuery.inArray($(this).attr('title'), attributeColumns) == -1) {
        attributeColumns.push($(this).attr('title'));
      }
    });
  }
  var headerRowHTML = "<tr><th>&nbsp;</th>";
  for (var i = 0; (i < attributeColumns.length && i < 3); i++) {
    headerRowHTML += "<th>"+attributeColumns[i]+"</th>";
  }
  headerRowHTML += "<th>&nbsp;</th></tr>";
  $("#cpa-product-feature-comparison").html(headerRowHTML);
  
  for (var i = 0; i < productResultData.length; i++) {
    var productRowHTML ="";
    productRowHTML +='<tr class="result-row">';
  	productRowHTML +='<td><a href="'+productResultData[i].find('product-page-url').text()+'" target="_blank" id="product-comparison-link-'+i+'"  item="'+i+'" class="product-comparison-link">'+productResultData[i].find('product-name').text()+'</a></strong></td>';
  	for (var ii = 0; (ii < attributeColumns.length && ii < 3); ii++) {
      if(productResultData[i].find('attribute[title='+attributeColumns[ii]+']').size() > 0) {
        productRowHTML += "<td>"+ productResultData[i].find('attribute[title='+attributeColumns[ii]+']').text()+"</td>";
      } else {
        productRowHTML += "<td>&nbsp;</td>";
      }
  	 
    }
  	productRowHTML +='<td class="last"><a href="'+productResultData[i].find('buy-url').text()+'" target="_blank" class="button buy">Buy</a></td>';
  	productRowHTML +='</tr>';
    $("#cpa-product-feature-comparison").append(productRowHTML);
    //$('#product-comparison-link-'+i).unbind("click").click(function() { populateProductView(parseInt($(this).attr('item'))) });
  }
  // if no attributes or only one product don't show quick compare
  if(attributeColumns.length >= 1 && productResultData.length > 1) {
    $("#cpa-product-view-select").show();
  } else {
    $("#cpa-product-view-select").hide();
  }
  
}
function trimHistoryElement(level) {
  var numberOfOldElements = 1;
  var numberOfNewElements = 1;
  if($("#cpa-history-element > li").size() < 1) {
   $("#cpa-history-element").append("<li><a href=\"#null\" id=\"my-requirements\">"+configurationXmlDoc.find("#historyElement-myRequirements").text()+"</a></li>"); 
    $("#my-requirements").unbind("click").click(selectProductGroup);
  }
  $("#cpa-history-element > li").each(function() {  
    
    if(level!=null && numberOfOldElements > level) {
      $(this).remove();
    } else {
      numberOfNewElements++;
    }
    numberOfOldElements++;
  });
}


function updateHistoryElement(id, title, level) {

//console.log('1');
  var numberOfOldElements = 1;
  var numberOfNewElements = 1;
  
  if($("#cpa-history-element > li").size() < 1) {
   $("#cpa-history-element").append("<li><a href=\"#null\" id=\"my-requirements\">"+configurationXmlDoc.find("#historyElement-myRequirements").text()+"</a></li>"); 
    $("#my-requirements").unbind("click").click(selectProductGroup);
  }

  $("#cpa-history-element > li").each(function() {  

//console.log('3-'+debugLoops++);    
    if(level!=null && numberOfOldElements >= level) {
      $(this).remove();
    } else {
      numberOfNewElements++;
    }
    numberOfOldElements++;
  });
  
  /*
  var treeID = "";
  var treeParts = id.split('-');  
  for (var i = 0; i < (treeParts.length-1); i++) {
    if(i!=0) {
      treeID+="-";
    }
    treeID+=treeParts[i];     
  }
  */
  var treeID = id;
    
  $("#cpa-history-element").append("<li class=\"arrow\"><a href=\"#null\" id=\"history-" + id + "\" tree-id=\"" + treeID + "\" element-depth=\"" + numberOfNewElements + "\">" + title + "</a></li>");
  $("#history-" + id).unbind("click").click(function() {
      /*
      if($(this).attr("element-depth") == 2) {
        selectProductGroup();
      } else {
      */  
        loadDecisionPage($(this).attr("tree-id"));
      //}  
      trimHistoryElement($(this).attr("element-depth"));
    });
//console.log('6');
}