Products = {
  productsURL: '/product/main', // not dry
  
  checkedToCompare: [],
	checkedToCompareCategories: [],
  checkedToCompareAlert: "You must first select at least two products to compare.",
	checkedToCompareUniqueCategories: 0,
	
	clickedStar: 0,
	
  getContent : function(params) {
		var checked = false;
		if ($j('#include_discontinued:checked').val() == 'true') {
			checked = true;
		}
    params = params.sub('#', '') + '&' + $j('#queryString').text() + '&discontinued=' + checked;
    var contentType = params.toQueryParams().type;
    var url = Products.productsURL;
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:params,
						onLoading: function(request){
							if ($('spinner_loader')){
								$j('span#spinner_loader').show();
							}
							if ($('spinner_loader_2')){
								$j('span#spinner_loader_2').show();
							}
							if ($$('p#discontinued img.spinner')){
								$j('#discontinued .spinner').css('display', 'inline');
							}
						},
						onComplete: function(request){
							if ($('spinner_loader')){
								$j('span#spinner_loader').hide();
							}
							if ($('spinner_loader_2')){
								$j('span#spinner_loader_2').hide();
							}
							if ($$('p#discontinued img.spinner')){
								$j('#discontinued .spinner').css('display', 'none');
							}
						}
					});
  },

	getReviews : function(params) {
		var checked = false;
		if ($j('#include_discontinued:checked').val() == 'true') {
			checked = true;
		}
    params = params.sub('#', '') + '&' + $j('#queryString').text() + '&discontinued=' + checked + '&comments=1';
    new Ajax.Updater('content_comments', window.location.pathname, { parameters: params, evalScripts: true, onLoading:function(){Element.show('page_spinner');}, onLoaded:function(){Element.hide('page_spinner');}, onComplete:function(){ initUI(); Products.addListeners(); window.location.href = '#content_comments'; } });
  },

  updateHash : function(s_param) {
    Products.updatedByClick = true;
    var params = new Hash(s_param.toQueryParams());
	if (typeof(params.get('page')) == "undefined"){
		params.set('page', 1);
	}
    var hash_params = new Hash(document.location.hash.sub('#', '').toQueryParams());
	if (params.get('query') == ""){
		params.unset('query');
		hash_params.unset('query');
	}
    document.location.hash = hash_params.merge(params).toQueryString();
    return document.location.hash;
  },

  checkHash : function() {
    if (window.pe)
      window.pe.stop();
    var current_value = document.location.hash;
    return new PeriodicalExecuter(function(){
      if (Products.updatedByClick) {
        Products.updatedByClick = false;
        return;
      }
      if (document.location.hash != current_value) {
        Products.getContent(document.location.hash);
      }
        
      current_value = document.location.hash;
    }, 1);
  },	

  compareProducts: function() {
    var compare = [];
    var url = '/product/compare/';
  	$j('span.product_id').each(function() {
  	  compare.push($j(this).text());
  	});
  	compare.push($j(this).find('span').text());
  	for(i=0; i<compare.length; i++) {
      url += (compare[i] + '-');
    }
    while(url.charAt(url.length - 1) == '-') {
      url = url.slice(0, -1);
    }
  	$j('#compare_wrapper').load(url + '?xhr=1');
  	return false;
  },
  
	removeDuplicateParams: function(params) {
		var split = params.split('&');
		var sorted = split.sort();
		var results = [];
		for (var i = 0; i < sorted.length; i += 1) {
			if (sorted[i + 1] != sorted[i]) {
        results.push(sorted[i]);
      }
		}
		return results.join('&');
	},
	
	prepareCompareButton: function() {
		var cookies = [];
		$j.each($j.cookies.filter('product_checked_'), function(i, val) {
			cookies.push(val);
		});
		uniq_cookies = cookies.uniq(); // Prototype
		if(cookies.length < 2) {
			Products.checkedToCompareAlert = "You must first select at least two products to compare.";
			$('compare_selected').removeClassName('okay');
		}
		else if (uniq_cookies.length > 1) {
			Products.checkedToCompareAlert = "Only products from the same category can be compared. Please uncheck conflicting products and try again.";
			$('compare_selected').removeClassName('okay');
		}
		else {
			Products.checkedToCompareAlert = "";
			$('compare_selected').addClassName('okay');
		}
	},
	
	clearCompareCookies: function() {
		$j.each($j.cookies.filter('product_checked_'), function(i, val) {
			$j.cookies.del(i);
		});
	},
	
  addListeners : function() {
	
		$j('p.helpful input').click(function() {
			var prid = $j(this).attr("class").replace("rate_", "");
			var dir = $j(this).val();
			$j('#rating_count_' + prid).load('/product_reviews/add_thumb?prid=' + prid + '&dir=' + dir);
		});
		
    $$('.pagination a').each(function(a) {
      //a.href = "#" + a.href.match("\\?(.+)").last();
      a.addClassName('remote');
			var search = window.location.search;
			search = search.replace(/page=\d+/g, '');
			var params = a.href.replace(/http.+\?/, '') + '&' + search;
			params = params.replace(/\?/g, '');
			params = params.replace(/&+/g, '&');
			params = params.replace(/&$/, '');
			query = Products.removeDuplicateParams(params);
			a.href = '?' + query;
    });

    $$('div#products_list .remote').each(function(a) {
      a.observe('click', function(e) {
	
        var el = e.element();
				var search = window.location.search;
				search = search.replace(/scope=\w+/g, '');
        var params = el.href.match("\\?(.+)").last() + '&' + search;
				params = params.replace(/\?/g, '');
				params = params.replace(/&+/g, '&');
				params = params.replace(/&$/, '');
				document.location.href = '?' + params;
				
        //Products.getContent(params);
        //Event.stop(e);
        //return false;
      });
    });

		$$('ul#comment_list .remote').each(function(a) {
      a.observe('click', function(e) {
        var el = e.element();
        var params = el.href.match("\\?(.+)").last() + '&' + window.location.search.replace('?', '') + '&review_update=1&id=' + $('id').value;
        Products.getReviews(params);
        Event.stop(e);
        return false;
      });
    });
	
	if($('include_discontinued')) {
	  $('include_discontinued').observe('click', function(e) {
					var scope = $j('#scopeSort a.openable').attr('href');
					var search = window.location.search;
					search = search.replace(/scope=\w+/g, '');
					search = search.replace(/discontinued=\w+/g, '');
					search = search.replace(/page=\d+/g, '');
					var params = scope + "&discontinued=" + this.checked + '&' + search;
					params = params.replace(/\?/g, '');
					params = params.replace(/&+/g, '&');
					params = params.replace(/&$/, '');
					query = Products.removeDuplicateParams(params);
					document.location.href = '?' + query;
          //var params = scope + "&discontinued=" + this.checked + "&" + window.location.search.replace('?', '');
          //Products.getContent(params);
          //return false;
      });
	}
    
    $j('.top_product_title a').mouseenter(function() {
        var title = this.title.toLowerCase();
				title = title.replace(/\W+/g, '_');
        var menu = $j('#product_menu_' + title);
        var link = $j(this);
        menu.css("display", "block");
        link.addClass("selected");
        $j(this).parent().mouseleave(function() {
            menu.css("display", "none");
            link.removeClass("selected");
        });
    });
    
		$j('ul.star_ratings.small li a').mouseenter(function() {
			var currentStar = $j(this).text();
			$j('ul.star_ratings.small li a').each(function() {
				if($j(this).text() <= currentStar) {
					$j(this).removeClass('off').addClass('on');
				}
				else {
					$j(this).removeClass('on').addClass('off');
				}
			});
			$j(this).parent().parent().mouseleave(function() {
        $j('ul.star_ratings.small li a').each(function() {
					if($j(this).text() <= Products.clickedStar) {
						$j(this).removeClass('off').addClass('on');
					}
					else {
						$j(this).removeClass('on').addClass('off');
					}
				});
      });
		});
		$j('ul.star_ratings.small li a').click(function() {
			Products.clickedStar = $j(this).text();
			$j('#product_rating_id').val(Products.clickedStar);
			return false;
		});
		
		$j('.check_to_compare').each(function() {
			var id = $j(this).next().attr('id').replace('checkbox_', '');
			if($j.cookies.get('product_checked_' + id)) {
				$j(this).attr('checked', true);
			}
		});
		
		$j('.check_to_compare').click(function() {
			var id = $j(this).next().attr('id').replace('checkbox_', '');
			if($j(this).attr('checked')) {
				$j.cookies.set('product_checked_' + id, $j('#checkbox_' + id).val());
			}
			else {
				$j.cookies.del('product_checked_' + id);
			}
			Products.prepareCompareButton();
		});
		
		/*
    $$('.check_to_compare').each(function(c) {
      c.observe('click', function(e) {
				var id = this.value;
        if(this.checked) {
					$j.cookies.set('product_checked_' + id, 'true');
          Products.checkedToCompare.push(id);
					Products.checkedToCompareCategories.push($('checkbox_' + id).value);
        }
        else {
					$j.cookies.del('product_checked_' + id);
	
          for(i=0; i<Products.checkedToCompare.length; i++) {
            if(Products.checkedToCompare[i] == this.value) {
              Products.checkedToCompare.splice(i, 1);
            }
          }
					for(i=0; i<Products.checkedToCompareCategories.length; i++) {
            if(Products.checkedToCompareCategories[i] == $('checkbox_' + id).value) {
              Products.checkedToCompareCategories.splice(i, 1);
            }
          }

        }
				if(Products.checkedToCompareCategories.length < 2) {
					Products.checkedToCompareAlert = "You must first select at least two products to compare.";
					$('compare_selected').removeClassName('okay');
				}
				else if (Products.checkedToCompareCategories.uniq().length > 1) {
					Products.checkedToCompareAlert = "Only products from the same category can be compared. Please uncheck conflicting products and try again.";
					$('compare_selected').removeClassName('okay');
				}
				else {
					Products.checkedToCompareAlert = "";
					$('compare_selected').addClassName('okay');
				}
        return false;
      });
    });
    */
    if($('compare_selected')) {
      $('compare_selected').observe('click', function(e) {
						if(Products.checkedToCompareAlert != '') {
							alert(Products.checkedToCompareAlert);
							Event.stop(e);
						}
						else {
							var cookies = [];
							$j.each($j.cookies.filter('product_checked_'), function(i, val) {
								cookies.push(i.replace('product_checked_', ''));
							});
							uniq_cookies = cookies.uniq(); // Prototype
	            this.form.action = '/product/compare/';
	            for(i=0; i<uniq_cookies.length; i++) {
	              this.form.action += (uniq_cookies[i] + '-');
	            }
	            this.form.action = this.form.action.slice(0, -1);
						}
        });
      }
      
    $$('div.product-search ul.select li a').each(function(a) {
          a.observe('click', function(e) {
          var el = e.element();
          if(this.id != 'all_categories_link') {
            $('search_category_id').value = el.href.match("\\?mpid=(.+)").last();
          }
          else {
            $('search_category_id').value = "";
          }
          Event.stop(e);
          return false;
        });
    });
    
    $$('tr.remove td a').each(function(a) {
          a.observe('click', function(e) {
          var colNumber = $j(this).parent().attr('col');
          $j('td[col='+colNumber+']').empty();
          Products.compareProducts();
          Event.stop(e);
          return false;
        });
    });
    
    $j('div.categories ul li.closed').toggle(function() {
      $j(this).addClass('opened').removeClass('closed');
      $j(this).next().find('ul').show();
    }, function() {
      $j(this).addClass('closed').removeClass('opened');
      $j(this).next().find('ul').hide();
    });

    $j('div.add-to-compare').click(function() {
  	    if ($j(this).children('ul.select').css("display") == "none") {
				    $j('ul.select').hide();
				    $j('div.add-to-compare').removeClass("opened");
				    $j(this).addClass('opened').children('ul.select').show();
			  }
        return false;
  	  });
  	  
	  /*$j('.remove_product').click(function() {
	      q = window.location.search.replace(/cat=[\w-]+&id=\d+/, '');
	      if(q == '?')
	        q = q.replace('?', '');
        window.location.href = window.location.pathname + q;
        return false;
    });*/
      
  	$j('div.add-to-compare ul.select a').click(Products.compareProducts);
    
    $j('div.thumbs img').click(function() {
			var width = $j(this).attr('class').replace('width_', '').replace(' ', '') + 'px';
    	var img = $j(this).attr('src').replace('small_square', 'large');
    	var large_img = $j(this).attr('src').replace('small_square', '');
    	$j('div.image img').attr('src', img);
    	$j('div.image a').attr('href', large_img);
			$j('#mainProductPhoto').css('width', width);
			$j('#mainProductPhoto').css('margin', '0 auto');
    });
		
    $j('.top_product_title').mouseenter(function() {
	      var title = this.firstChild.title.toLowerCase();
	      var menu = $j('#product_menu_' + title);
	      $j('.additional').css("display", "none");
	      menu.css("display", "block");
	      menu.mouseleave(function() {
                menu.css("display", "none");
    		  });
	  });
	  
	/*$j('div.thumbs li').mouseenter(function() {
		if(typeof(original) == 'undefined') {
			original = $j('div.image img').attr('src');
		}
		var img = $j(this).find('img').attr('src').replace('small_square', 'large');
	 	$j('div.image img').attr('src', img)
     $j(this).mouseleave(function() {
		$j('div.image img').attr('src', original)
  		});
 	});*/

	  $j('div.thumbs li img').qtip({
       content: $j(this).alt,
       show: 'mouseover',
       hide: 'mouseout',
       position: {
         corner: {
           target: 'bottomMiddle',
           tooltip: 'topLeft'
         }
       },
       style: { 
         background: '#e2e2e2',
         color: '#000',
         fontWeight: 'bold',
         fontSize: 11,
         border: {
           width: 0
         }
      }
    })
    
		$j('#mainProductImage').qtip({
       content: $j(this).alt,
       show: 'mouseover',
       hide: 'mouseout',
       position: {
         corner: {
           target: 'topRight',
           tooltip: 'topRight'
         }
       },
       style: { 
         background: '#e2e2e2',
         color: '#000',
         fontWeight: 'bold',
         fontSize: 11,
         border: {
           width: 0
         }
      }
    });

		$j('div.compare .sort li:empty').each(function() {
			$j(this).css('display', 'none');
		});

		$j('ul#comment_list ul.select li:empty').each(function() {
			$j(this).css('display', 'none');
		});
		
	
    $j('div.product-show div.add-to-compare ul.select li a').click(function() {
      var selected_id = $j(this).find('span').text();
      var current_id = $j('#id').val();
      window.location = '/product/compare/' + current_id + '-' + selected_id;
      return false;
    });
    
    window.pe = Products.checkHash();
		
		if(window.location.href.search('/product/main') > 0) {
			Products.prepareCompareButton();
		}
		else {
			Products.clearCompareCookies();
		}
  }
  
  
}

$j(document).ready(function(){
  Products.addListeners();
});