jQuery(document).ready(function() {
	var productSort = new ProductSort();
	productSort.init();
});

var ProductSort = function() {
  
  
	var ALL_TYPES = "all-types";
	var ALL_BRANDS = "all-brands";
	var ALL_SCREEN_SIZES = "all-screens-sizes";
  var ALL_WEIGHTS = "all-weights";
  var ALL_SCREEN_SIZES_MSG = '(All screen sizes)';
  var ALL_WEIGHTS_MSG = '(All weights)';
  var COOKIE_NAME = 'comgobiproductsviewed';
  
  
  var dataSource = "/gobi_product_viewer/data/products.txt";
	var productData = {};
	var productSet = [];
	var productMatches = [];
	var maxScreenSize = 0;
	var minScreenSize = 0;
  var selectedScreenSize = 0;
  var screenSizesSliderHTML = '<h6>Screen Size:</h6><div class="slider-wrap"><div id="screen-size-slider"></div></div><div class="scale">All</div><div class="value"></div><div class="illos"><div class="illo i1"></div></div>';
  var maxWeight = 0;
  var minWeight = 0;  
  var selectedWeight = 0;
  var weightsSliderHTML = '<h6>Weight:</h6><div class="slider-wrap"><div id="weight-slider"></div></div><div class="scale">All</div><div class="value"></div><div class="illos"><div class="illo i1"></div></div>';
  var keywords = [];
  var typeNames = [];
  
  var createInterval = 0;
  var createProductCount = 0;

	var init = function() {  
    // Cross-browser styles for the form controls
    //$("#product-select select").uniform();
    // Attempt to retrieve product data
    $(window).load(function () {
      $.getJSON(dataSource, function(data, textStatus) {
        switch(textStatus) {
          case 'timeout':
            onDataError();
          break;
          case 'error':
            onDataError();
          break;
          case 'notmodified':
            onDataError();
          break;
          case 'parsererror':
            onDataError();
          break;
          case 'success': 
            productData = data;
            initControls();
          break;
        }
      });
    });  
  }
  this.init = init; 
  
  
  // Data error
  var onDataError = function() {
    $('#loading-products').css({display:'none'});
    $('#loading-error').css({display:'block'});    
  }
  this.onDataError = onDataError;
  
  
  // First initialization of controls
  var initControls = function() {
    initProductTypes();
    initKeywordSearch();
    initJumpList();
    initCheckBrandsButtons();
    initResetButton();
    initProductDetails();
    onChangeType(ALL_TYPES);
  }
  this.initControls = initControls;
  
  var getValidItemType = function (t) {
    t = t.replace(/\//g, "");
    return t;
  }
  this.getValidItemType = getValidItemType;

  // Build product types list
  var initProductTypes = function() {
    // Clear out old list
    $('#control-product-type .button-group').empty();
    var types = [];
    // Build list
    $.each(productData.items, function(i, item) {
      if (!item) return;
      typeNames.push(item.type);
      types.push(getValidItemType(item.type));
    });
    types = makeArrayUnique(types);
    typeNames = makeArrayUnique(typeNames);
    
    // Add the all button
    $('#control-product-type .button-group').append('<a class="button" href="#" id="' + ALL_TYPES + '"><span>All</span></a>');                                             
    // Add the type buttons
    $.each(types, function(i, type) {
      $('#control-product-type .button-group').append('<a class="button" id="' + type + '" href="#"><span>' + typeNames[i] + '</span></a>');
    });
    // Add click handlers to each button
    $('#control-product-type .button-group a').click(function(e){
      onChangeType($(this).attr('id'));
      return false;
    });
  }
  this.initProductTypes = initProductTypes;
  
  
  var initKeywordSearch = function() {
    $('#keyword-search').click(function(e){return false;});
    
    $("#control-keyword-search input").focus(function(src) {
      if ($(this).val() == $(this)[0].title) {
        //$(this).parent().removeClass("disabled");
        $(this).val("");
      }
    });
    
    $("#control-keyword-search input").blur(function() {
      if ($(this).val() == "") {
        $(this).val($(this)[0].title);
        $(this).parent().addClass("disabled");        
      }
    });
    
    $("#control-keyword-search input").keyup(function(e) {
      if ($(this).val().length > 0) {
        $(this).parent().removeClass("disabled");     
        $('#keyword-search').bind("click", onKeywordSearch);
        if(e.keyCode == 13) {
		        onKeywordSearch();
		        $(this).blur();
	       }
      } else {
        $(this).parent().addClass("disabled");
        $('#keyword-search').unbind("click", onKeywordSearch);                  
      }
    });
    
    $("#control-keyword-search input").blur();
    
    keywords = [];
    $.each(productData.items, function(i, item) {
      if (!item) return;
      var obj = {};
      var typeArray = item.type.split(' ');
      var brandArray = item.brand.split(' ');
      var titleArray = item.title.split(' ');
      var processorArray = item.processor.split(' ');    
      var batteryArray = item.battery.split(' ');
      var featuresArray = item.features.split(' ');
      var descriptionArray = item.details.split(' ');
      
      var combined = typeArray.concat(brandArray);
      combined = combined.concat(titleArray);
      combined = combined.concat(processorArray);
      combined = combined.concat(batteryArray);
      combined = combined.concat(featuresArray);
      combined = combined.concat(descriptionArray);
      obj.id = item.id;
      obj.keywords = combined;
      keywords.push(obj);
    });
  }
  this.initKeywordSearch = initKeywordSearch;

  
  var initJumpList = function() {
    $('#product-select').empty().append('<select></select>');
    var html = "<option value='none'>Jump to a product</option>";
    $.each(productData.items, function(i, item) {
      if (!item) return;
      html += '<option value="prod-' + item.id + '">' + item.title + '</option>';
    });
    $('#product-select select').append(html);
    $("#product-select select").uniform();
    
    $("#product-select select").change(function(){
      showProductDetails($(this).val());
    });
  }
  this.initJumpList = initJumpList;
  
  
  // Build brands check box list
  var initBrands = function() {
    // Clear out old list
    $('#brand-checkboxes').empty();
    // Deactive 'uncheck all' link 
    $('#uncheck-brands').addClass('disabled');
    // Build brands list, ignore duplicates
    var brands = [];    
    $.each(productSet, function(i, item) {
      if (!item) return;
      brands.push(item.brand);
    });
    brands = makeArrayUnique(brands);
    // Enable uncheck all 
    if (brands.length > 0) $('#uncheck-brands').removeClass('disabled');
    // Create check boxes
    $.each(brands, function(i, brand) {
      $('#brand-checkboxes').append('<label><input type="checkbox" checked="checked" name="' + brand + '" />' + brand + '</label>');
    });
    // Style checkboxes
    $("#brand-checkboxes :checkbox").uniform();
    // Add click handlers
    $("#brand-checkboxes :checkbox").click(onChangeBrands);
  }
  this.initBrands = initBrands;
  
  
  // Create a screen size slider
  var initScreenSizes = function() {
    // Build screen sizes list, ignore duplicates
    var screensizes = [];    
    $.each(productSet, function(i, item) {
      if (!item) return;
      screensizes.push(item.num_screensize);
    });
    screensizes = makeArrayUnique(screensizes);
    screensizes.sort(sortNumbers);
        
    // Empty old slider and create new one
    $("#control-screen-size").empty().append(screenSizesSliderHTML);
    
    if (screensizes.length > 1) {
      
      var min = Math.floor(screensizes[0]);      
      var max = Math.ceil(screensizes[screensizes.length - 1]);
      
      minScreenSize = min;
      maxScreenSize = max;
      selectedScreenSize = maxScreenSize;      
            
      // Set initial text
      var msg = '(' + min + '" to ' + max + '" Screens)';
      $("#control-screen-size .value").text(msg);
      
      $("#screen-size-slider").slider({
        range: true,
		    min: min,
		    max: max,
		    values: [min, max],
		    slide: onChangeScreenSizes
		  });
		  $("#control-screen-size").removeClass('disabled');
		  
    } else {
    
		  $("#control-screen-size").addClass('disabled');    
      selectedScreenSize = screensizes[0];
      minScreenSize = 0;
      maxScreenSize = 9999;
    }
  }
  this.initScreenSizes = initScreenSizes;
  
  
  var initWeights = function() {
    // Build screen sizes list, ignore duplicates
    var weights = [];    
    $.each(productSet, function(i, item) {
      if (!item) return;
      weights.push(item.num_weight);
    });
    weights = makeArrayUnique(weights);
    weights.sort(sortNumbers);
    
    // Empty old slider and create new one
    $("#control-weight").empty().append(weightsSliderHTML);
    $("#control-weight .value").text(ALL_WEIGHTS_MSG);

    if (weights.length > 1) {
      var min = Math.floor(weights[0]);
      var max = Math.ceil(weights[weights.length - 1]);
      var step = (max - min)/3; // 4 stops total
      
      minWeight = min;
      maxWeight = max;
      selectedWeight = max;
            
      var msg = '(' + minWeight + ' lbs to ' + maxWeight + ' lbs)';
      $("#control-weight .value").text(msg);     

      $("#weight-slider").slider({
		    range: true,
		    min: min,
		    max: max,
		    values: [min, max],		    
		    slide: onChangeWeights
		  });
		  $("#control-weight").removeClass('disabled');
		  
    } else {
		  $("#control-weight").addClass('disabled');    
      selectedWeight = weights[0];
      minWeight = 0;
      maxWeight = 9999;
    }
  }
  this.initWeights = initWeights;

  
  // Add click handler to Reset Filters button
  var initResetButton = function() {  
    $('#results #reset-filters').click(function(e) {
    $("#control-keyword-search input").val('').blur();        
      onChangeType(ALL_TYPES);
      $("#check-brands").css({display:'none'});
      $("#uncheck-brands").css({display:'block'});	  	  
      return false;
    });
  };
  this.initResetButton = initResetButton;
  
  
  // Add click handler to Uncheck All button
  var initCheckBrandsButtons = function() {  
    $('#uncheck-brands').click(function(e) {
      $("#brand-checkboxes :checkbox").attr({checked:''});
      $("#brand-checkboxes .checker span").removeClass('checked');
      $("#brand-checkboxes :checkbox").change();
      $(this).css({display:'none'});
      $("#check-brands").css({display:'block'});
	  onChangeBrands();	  
      return false;
    });
    
    $('#check-brands').click(function(e) {
      $("#brand-checkboxes :checkbox").attr({checked:'checked'});
      $("#brand-checkboxes .checker span").addClass('checked');
      $("#brand-checkboxes :checkbox").change();
      $(this).css({display:'none'});
      $("#uncheck-brands").css({display:'block'});
	  onChangeBrands();
	  return false;
    });
  };
  this.initCheckBrandsButtons = initCheckBrandsButtons;
  
  
  var initProductDetails = function() {
    
    $('#product-details-mask').click(function(e){
		  hideProductDetails();
		  return false;
		});
		
		$('#product-details-close').click(function(e){
		  hideProductDetails();
		  return false;
		});	
		
  }
  this.initProductDetails = initProductDetails;


  // Find products that meet selected criteria
  var findProducts = function() {  
    productMatches = [];

    $.each(productSet, function(i, item) {
      if (!item) return;
      var isBrand = false;
      var isScreenSize = false;
      var isWeight = false;
      // Brand check
      $("#brand-checkboxes :checkbox").each(function(ii){
        if ($(this).attr('name') == item.brand) {
          if ($(this).attr('checked')) {
            isBrand = true;
          }
        }
      });
      // Screen size check
      if (item.num_screensize >= minScreenSize && item.num_screensize <= maxScreenSize) {
        isScreenSize = true;
      }
      if ($("#control-screen-size").hasClass('disabled')) {
        isScreenSize = true;
      }
      
      // Weight size check
      if (item.num_weight >= minWeight && item.num_weight <= maxWeight) {  
        isWeight = true;
      }
      
      if ($("#control-weight").hasClass('disabled')) {
        isScreenSize = true;
      }
      
      // Final check
      if (isBrand && isScreenSize && isWeight) {
        productMatches.push(item);
      }
    });
    showProducts();
  }
  this.findProducts = findProducts;
  
  
  // Show found products
  var showProducts = function() {
    // Clear out old products
    clearInterval(createInterval);
    $('#progrid').empty();
    // Creat new products
    var html = '';
    var colCount = 0;
    var lastClass = '';
    var cookieClass = '';
    var id = '';
    $.each(productMatches, function(i, item) {
      if (!item) return;
      colCount++;
      if (colCount > 3) { 
        lastClass = "last";
        colCount = 0;
      } else if (productMatches.length-1 == i) {
        lastClass = '';
      } else {
        lastClass = '';
      }
      
      id = 'prod-' + item.id;
      var isCookied = $.cookie(id);
      cookieClass = "";
      if (isCookied) cookieClass = "viewed";
      
      html += '<a class="prod ' + lastClass + ' ' + cookieClass + '" id="' + id + '" href="' + item.url + '">';
      html +=   '<img src="' + item.image1 + '" width="180" height="180" />';
      html +=   '<span class="make">' + item.brand + '</span>';
      html +=   '<span class="model">' + item.title + '</span>';
      html +=   '<span class="details">';
      html +=     '<span class="make">' + item.brand + '</span>';
      html +=     '<span class="model">' + item.title + '</span>';
      html +=     '<span class="goto">Go to product details</span>';
      html +=     '<span class="specs">';
      if (item.num_screensize > 0) html += '<span class="label">Screen Size:</span><span class="spec">' + item.num_screensize + ' inches</span>';
      if (item.num_weight > 0) html += '<span class="label">Weight:</span><span class="spec">' + item.num_weight + ' pounds</span>';
      if (item.processor.length > 0) html += '<span class="label">Processor:</span><span class="spec">' + item.processor + '</span>';
      if (item.battery.length > 0) html += '<span class="label">Battery Life:</span><span class="spec">' + item.battery + '</span>';
      if (item.features.length > 0) html += '<span class="label">Features:</span><span class="spec">' + item.features + '</span>';
      html +=     '</span>';
      html +=   '</span>';
      html +=   '<span class="viewed">Viewed Item</span>';
      html += '</a><!-- /prod -->';
    });
    
    // Plunk the text blob into the DOM
    $('#progrid').append(html);
    
    // Assign click handlers to each product
    $('.prod').click(function(e) {
      showProductDetails($(this).attr('id'));
      return false;
    }).hover(
      function () {
        $('.details', this).css({opacity:0}).show().fadeTo("fast", 1.0, function(){ if ($.browser.msie) { this.style.removeAttribute("filter")}} );
      }, 
      function () {
        $('.details', this).fadeTo("fast", 0.0);
      }
    ).css({opacity: 0});
    
    $('.prod .details').hide();
  
    // Make sure the loading indicator isn't showing
    $('#loading-products').css({display:'none'});
    
    // Update results
    $('#results').css({display:'block'});
    var rCount = (productMatches.length) + ' Products';
    if (productMatches.length == 1) rCount = '1 Product';
    $('#results .count').html(rCount);
    
    // Begin showing products
    createProductCount = 0;
    createInterval = setInterval(showProduct, 100);
  }
  this.showProducts = showProducts;
  
  
  var showProduct = function() {
    if (createProductCount >= productMatches.length) {
      clearInterval(createInterval);
      return;
    }
    var item = productMatches[createProductCount];
    var id = '#prod-' + item.id;
    $(id).fadeTo('slow', 1.0, function(){ if ($.browser.msie) { this.style.removeAttribute("filter")} });
    
    createProductCount++;
  };
  this.showProduct = showProduct;
  
  var showProductDetails = function(id) {
      
    $.cookie(id, 'viewed', { expires: 1 });
  
    var prodId = id.split('-')[1];
    var prod;
    $.each(productData.items, function(i, item) {
      if (!item) return;
       if (item.id + '' == prodId) prod = item;
    });    
    if (prod) {
    
      $('#'+ id).addClass('viewed');
    
      var html = '';
      
      // Title
      html += '<div id="product-details-title">' + prod.brand + ' ' + prod.title + '</div>';
      
      // Thumbs
      html += '<div id="product-details-thumbs">';
        html += '<a class="showing" href="#"><img src="' + prod.image1 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
        if (prod.image2 && prod.image2.length > 0) html += '<a href="#"><img src="' + prod.image2 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
        if (prod.image3 && prod.image3.length > 0) html += '<a href="#"><img src="' + prod.image3 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
        if (prod.image4 && prod.image4.length > 0) html += '<a href="#"><img src="' + prod.image4 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
        if (prod.image5 && prod.image5.length > 0) html += '<a href="#"><img src="' + prod.image5 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
        if (prod.image6 && prod.image6.length > 0) html += '<a href="#"><img src="' + prod.image6 + '" /><span class="showing">&nbsp;</span><span class="ready">&nbsp;</span></a>';
      html += '</div>';
      
      // Big image
      html += '<img id="product-details-image" src="' + prod.image1 + '" />';
      
      // Features List
      html += '<dl id="product-details-feature-list">';
        if (prod.screensize) html += '<dt>Screen Size:</dt><dd>' + prod.screensize + '"</dd>';
        if (prod.weight) html += '<dt>Weight:</dt><dd>' + prod.weight + ' lbs.</dd>';
        if (prod.processor && prod.processor.length > 0) html += '<dt>Processor:</dt><dd>' + prod.processor + '</dd>';
        if (prod.battery && prod.battery.length > 0) html += '<dt>Battery Life:</dt><dd>' + prod.battery + '</dd>';
        if (prod.features && prod.features.length > 0) html += '<dt>Features:</dt><dd>' + prod.features + '</dd>';
      html += '</dl>';
      
      // Description
      html += '<div id="product-details-description">' + prod.details + '</div>';
      
      // Links
      html += '<ul id="product-details-links">';
      html += '<li class="external"><a target="_blank" href="' + prod.brandLink + '">' + prod.brandLinkText + '</a></li>';
      html += '<li class="print"><a href="#">Print description</a></li>';        
      html += '</ul>';

      // Create DOM elements
      $('#product-details-content').empty().append(html);
      
      // Fade-in the large image when it changes src
      $('#product-details-image').load(function() {
        $(this).stop().animate({ opacity: 1.0}, 333);
      });
    
      // Thumbnail click handlers
      $('#product-details-thumbs a').click(function() {
        if ($(this).hasClass('showing')) return false;
        $('#product-details-thumbs a').removeClass('showing');
        $(this).addClass('showing');
        var imgSrc = ($('img', this).attr('src'));
        $('#product-details-image').stop().animate({ opacity: 0.0}, 0).attr('src', imgSrc);
        return false;
      });

      // Print click handler
      $('.print').click(function(e){
		    printProductDetails();
		    return false;
		  });
    
      //Get the screen height and width
		  var maskHeight = $(document).height();
		  var maskWidth = $(window).width();
	    
		  //Set heigth and width to mask to fill up the whole screen
		  $('#product-details-mask').css({'width':maskWidth,'height':maskHeight, opacity:0}).show().fadeTo("fast", 0.6);
	    
		  //Get the window height and width
		  var winH = $(window).height();
		  var winW = $(window).width();
		  winW = 1000; // Don't center in browser
                
		  //Set the popup window to center
		  $('#product-details').css('top',  winH/2-$('#product-details').height()/2);
		  $('#product-details').css('left', winW/2-$('#product-details').width()/2);
	    
		  //transition effect
		  $('#product-details').fadeIn(400);
    }
  }
  this.showProductDetails = showProductDetails;
  
  
  var hideProductDetails = function() {
    $('#product-details-mask').hide();
		$('#product-details').hide();		
		//$("#product-select").val('-1');
		$("#product-select select option:contains('Jump')").attr("selected", "selected");
		$("#product-select select").trigger('change');
  }
  this.hideProductDetails = hideProductDetails;
  
  
  var printProductDetails = function() {
    window.print();
  }
  this.printProductDetails = printProductDetails;


  var onChangeType = function(id) {
    matchFound = false;
    if (id == ALL_TYPES) {
      matchFound = true;
      productSet = productData.items.slice(); // By default all products are selected
    } else {
      productSet = [];
      $.each(productData.items, function(i, item) {
        if (item) {
          if (getValidItemType(item.type) == id) { 
          productSet.push(item); 
          matchFound = true;
        }
        }
      });
    }
    if (matchFound) {
      $('#control-product-type .button-group a').removeClass('selected');
      $('#control-product-type .button-group #' + id).addClass('selected');
      $("#control-keyword-search input").val('').blur();
      initBrands();
      initScreenSizes();
      initWeights();
      findProducts();
    }     
  }
  this.onChangeType = onChangeType;
  
  
  var onChangeBrands = function() {
    var isSelected = false;
    $("#brand-checkboxes :checkbox").each(function(i){
      if ($(this).attr('checked')) {
        isSelected = true;
      }
    });  
    
    if (isSelected) {
      $('#uncheck-brands').removeClass('disabled');
    } else {
      $('#uncheck-brands').addClass('disabled');
    }
  
    findProducts();
  }
  this.onChangeBrands = onChangeBrands;
  
  
  var onChangeScreenSizes = function(event, ui) {
    var adjustedValue = truncateNumber(ui.value);
    minScreenSize = truncateNumber(ui.values[0]);
    maxScreenSize = truncateNumber(ui.values[1]);
    var msg = '(' + minScreenSize + '" to ' + maxScreenSize + '" Screens)';
    $("#control-screen-size .value").text(msg);
    findProducts();
  }
  this.onChangeScreenSizes = onChangeScreenSizes;
  
  
  var onChangeWeights  = function(event, ui) {
    var adjustedValue = truncateNumber(ui.value);
    minWeight = truncateNumber(ui.values[0]);
    maxWeight = truncateNumber(ui.values[1]);
    var msg = '(' + minWeight + ' lbs to ' + maxWeight + ' lbs)';
    $("#control-weight .value").text(msg);        
    findProducts();
  }
  this.onChangeWeights = onChangeWeights;
  
  
  var onKeywordSearch = function(e) {
    $('#control-product-type .button-group a').removeClass('selected');

    var val = $("#control-keyword-search input").val();
    var matches = [];
    
    $.each(keywords, function(i, obj) {
      if (!obj) return;
      $.each(obj.keywords, function(ii, word) {
        if (!word) return;
        if (word.toLowerCase().indexOf(val.toLowerCase()) != -1) matches.push(obj);
      });
    });
    
    matches = makeArrayUnique(matches);
    
    productSet = [];
    $.each(productData.items, function(i, item) {
      if (!item) return;
      $.each(matches, function(ii, obj) {
        if (!obj) return;
        if (item.id == obj.id) productSet.push(item);
      });
    });
    
    productSet = makeArrayUnique(productSet);

    initBrands();
    initScreenSizes();
    initWeights();
    findProducts();
        
    return false;
  }
  this.onKeywordSearch = onKeywordSearch;
  
  var makeArrayUnique = function(a) {
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++) {
      for(var x = 0, y = r.length; x < y; x++) {
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
  }
  this.makeArrayUnique = makeArrayUnique;
  
  
  var sortNumbers = function(a,b) {
    return(a-b);
  }
  this.sortNumbers = sortNumbers;
  
  
  var truncateNumber = function(num) {
    var adjustedValue = num + '';
    if (adjustedValue.indexOf('.') != -1) {
      var decimal = adjustedValue.split('.')[1];
      decimal = decimal.substring(0,1)
      adjustedValue = adjustedValue.split('.')[0] + '.' + decimal;
    }
    return adjustedValue;
  }
  this.truncateNumber = truncateNumber;

  
  var log = function() {
    if(console) {
      console.log.apply(console, arguments);
    }
  }
  this.log = log;




}



    

