document.observe('dom:loaded', function(){
  setup();
  changeDefaultValue('search_input', 'Whatcha looking for?');
  var inpts = $$('.quantity input');
  inpts.each(function(inp){
    changeDefaultValue(inp, 'QTY');
  });
});
// the myLists array holds the contents of MyList: array[productID] = quantity
myLists = new Object();

/**
* Saves the cookie that holds the products and quantities.
*/
function saveCookie() {
	var cookieString = new Array();
	var counter_total = 0;

	for (var i in myLists) {
		if(myLists.hasOwnProperty(i)) {
			if((myLists[i]-0) > 0) {
				var s = i+'_'+myLists[i];
				cookieString[cookieString.length] = s;
				counter_total++;
			}
		}
	}

	setCounter(counter_total);

	if(cookieString.length > 0) {
		document.cookie = 'MyList=' + cookieString.join('-') +';path=/';
	} else {
		document.cookie = 'MyList=1; expires=Thu, 01-Jan-70 00:00:01 GMT;path=/;';
	}
}

function setCounter(ncnt) {
	var counter = $("mylist_count");
	counter.innerHTML=ncnt+"";
}

/**
* Reads cookie parses it for MyList info and
* stores that info in the myList array.
*/
function loadCookie() {
	var cookie = document.cookie.split('; ');
	var counter_total = 0;

	for (var i=0; i < cookie.length; i++) {
		var crumb = cookie[i].split('=');
		if ('MyList' == crumb[0] && crumb[1]) {
			var products = crumb[1].split('-');
			counter_total = products.length;
			for (var j=0; j<products.length; j++) {
				product = products[j].split('_');
				if(product[1]-0 > 0) {
					myLists[product[0]] = product[1];
//					counter_total = (counter_total-0)+(product[1]-0);
					nodes = document.getElementsByName("input_"+product[0]);
					for(k=0;k<nodes.length;k++) {
						nodes[k].value=product[1];
					}
				}
			}
		}
	}
	var counter = $("mylist_count");
	counter.innerHTML=counter_total;
}

function addProduct(elem, event, productID) {
	var quantity;
	var inputField = $('input_'+productID);
	var prodContID = $('product_'+productID);
	var relatedProdContID = $('related_item_'+productID);

	if(myLists[productID]) {
		quantity = myLists[productID];
		quantity = (quantity-0) + 1;
	} else {
		quantity = 1;
	}
	// TODO
	myLists[productID] = quantity;

	inputField.value = quantity;

	new Effect.Parallel([
	  new Effect.Highlight('mylist_link', {restorecolor:'#7ac142'}),
  	//new Effect.Highlight('input_'+productID, {restorecolor:'#fff'})
	]);

  if (inputField.value > 0) {
    if(prodContID){
      prodContID.addClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.addClassName('added-to-my-list');
    }
    inputField.removeClassName('empty');
    changeDefaultValue(inputField, 'QTY');
  } else {
    if(prodContID){
      prodContID.removeClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.removeClassName('added-to-my-list');
    }
    inputField.addClassName('empty');
    changeDefaultValue(inputField, 'QTY');
  }
	saveCookie();
}

function removeProduct(elem, event, productID) {
	var quantity;
	var inputField = $('input_'+productID);
	var prodContID = $('product_'+productID);
	var relatedProdContID = $('related_item_'+productID);

	if(myLists[productID]) {
		quantity = myLists[productID];
		quantity = quantity - 1;
	} else {
		quantity = 0;
	}

	if(quantity > 0) {
		inputField.value=quantity;
		myLists[productID] = quantity;
	} else {
		inputField.value='';
		myLists[productID] = 0;
	}
	new Effect.Parallel([
	  new Effect.Highlight('mylist_link', {restorecolor:'#7ac142'}),
    //new Effect.Highlight(inputField, {restorecolor:'#fff'})
	]);
  if (inputField.value > 0) {
    if(prodContID){
      prodContID.addClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.addClassName('added-to-my-list');
    }
    inputField.removeClassName('empty');
    changeDefaultValue(inputField, 'QTY');
  } else {
    if(prodContID){
      prodContID.removeClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.removeClassName('added-to-my-list');
    }
    inputField.addClassName('empty');
    changeDefaultValue(inputField, 'QTY');
  }
	saveCookie();
}

function enterProduct(elem, event, productID) {

	var quantity;
	var elem = $(elem);
	var prodContID = $('product_'+productID);
	var relatedProdContID = $('related_item_'+productID);

	if (elem.value > 0) {
	  if(prodContID){
      prodContID.addClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.addClassName('added-to-my-list');
    }
    //new Effect.Highlight(elem, {endcolor: '#7ac142',restorecolor: '#7ac142'});
  } else {
    if(prodContID){
      prodContID.removeClassName('added-to-my-list');
    } else if (relatedProdContID) {
      relatedProdContID.removeClassName('added-to-my-list');
    }
    //new Effect.Highlight(elem, {endcolor: '#fff',restorecolor: '#fff'});
  }

	if(isNaN(elem.value)) {
		elem.value = "";
	} else {
		myLists[productID] = elem.value;
		saveCookie();
	}

	new Effect.Highlight('mylist_link', {endcolor: '#7ac142',restorecolor: '#7ac142'});
}

function clearMyList() {
  Effect.ScrollTo('header');
  var answer = confirm("Do you really want to clear your list?");
  if (answer) {
    document.cookie = 'MyList=1; expires=Thu, 01-Jan-70 00:00:01 GMT;path=/;';
  	window.location.reload();
  }
  return false;
}

function changeDefaultValue(el, defVal) {
  var el = $(el);

  if(el.value === null || el.value === '' || el.value === 0) {
    el.value = defVal;
    el.addClassName('empty');
  }
  else if (el.value === defVal) {
    el.addClassName('empty');
  }
  el.observe('click', function(event) {
    if(el.value === defVal) {
      el.value = '';
      el.removeClassName('empty');
    }
  });
  el.observe('focus', function(event) {
    if(el.value === defVal) {
      el.value = '';
      el.removeClassName('empty');
    }
  });
  el.observe('blur', function(event) {
    if (el.value === null || el.value === '') {
      el.value = defVal;
      el.addClassName('empty');
    }
  });
}

function toggleElement(el, q) {
	Effect.toggle(el, 'blind', {queue: 'end'});
	return false;
}

function deleteItem(itemContainer) {
  new Effect.Parallel([
    new Effect.Highlight(itemContainer),
    $(itemContainer).fade(),
    Effect.BlindUp(itemContainer)
  ]);
}

function showSuccess() {
  Effect.Fade('my_list', {queue: 'front'});
  Effect.ScrollTo('header');
  Effect.Appear('success_message', {queue: 'end'});
	document.cookie = 'MyList=1; expires=Thu, 01-Jan-70 00:00:01 GMT;path=/;';
	setCounter(0);
	return false;
}
function toggleForm(el, form, enemybtn, enemy) {
  var el = $(el);
  var form = $(form);
  var enemybtn = $(enemybtn);
  var enemy = $(enemy);

  if(enemy && enemy.visible()) {
   Effect.BlindUp(enemy);
  }
  el.toggleClassName('disabled');
  if(enemybtn) {
    enemybtn.removeClassName('disabled');
  }
  toggleElement(form, 'front');
  Effect.ScrollTo(el, {queue: 'end'});

  return false;
}
function createProduct(categoryID) {
	var node = $('products_form'+categoryID);
	if(node) {
		if(node.className=='products_form') {
			node.className='products_form_open';
			$('products_form_prodid'+categoryID).value=0;
			$('products_form_catid'+categoryID).value=categoryID;
		  Effect.toggle(node, 'blind');
		} else {
			node.className='products_form';
			Effect.toggle(node, 'blind');
		}
	}
	return false;
}
function getAutoSelectionId(text, li) {
	var prodId = text.id.slice(text.id.indexOf('Name')+4);
	var hidden = $('RelatedId'+prodId);
	if(hidden) {
		hidden.value=li.id;
	}
	return false;
}
function setup() {
  var catTitles = $$("#products-list .category-name");
  var prodHeaders = $$("#products-list .product-name");
  var relHeaders = $$("#products-list .related-items-title");

  $$('.related-products .sub-list, .products_form, .edit_product_form_container, #mylists_form, #quicklists_form, #success_message').invoke('hide');

  prodHeaders.invoke('addClassName', 'trigger');
  catTitles.invoke('addClassName', 'trigger');

  catTitles.each(function(ct) {
    new Insertion.Bottom(ct, '<small>&nbsp;Expand/Collapse All</small>');
    ct.observe('click', function(event) {
      var nephs = this.next('ul').descendants().grep(new Selector('.product-content'));
      var nephStyles = nephs.invoke('getStyle', 'display').grep('none');
      if(nephStyles.any()) {
        //nephs.invoke('show');
        Effect.multiple(nephs, Effect.BlindDown, {speed:0.01});
      } else {
        //nephs.invoke('hide');
        Effect.multiple(nephs, Effect.BlindUp, {speed:0.01});
      }
    });
  });

  prodHeaders.each(function(h) {
    new Insertion.Bottom(h, '<small>&nbsp;Expand/Collapse</small>');
    h.observe('click', function(event) {
      if(this.hasClassName('product-name')) {
        var sibling = this.up('.product-header').next('.product-content');
      } else {
        var sibling = this.next('ul');
      }
      Effect.toggle(sibling, 'blind')
    });
  });

  relHeaders.each(function(h) {
    new Insertion.Top(h, '<div class="expand-collapse">&nbsp;Expand/Collapse</div>');
    h.observe('click', function(event) {
      if(this.hasClassName('product-name')) {
        var sibling = this.up('.product-header').next('.product-content');
      } else {
        var sibling = this.next('ul');
      }
      Effect.toggle(sibling, 'blind')
    });
  });
};

// handles errors on Mylist page
var ErrorHandler = {

		recreateCakeLabelId: function(prefix, str) {
			var sp = str.split(/_/ig);
			for (intsp = 0; intsp < sp.length; intsp++)
				prefix += sp[intsp].substr(0, 1).toUpperCase() + sp[intsp].substr(1).toLowerCase();
			return prefix;
		},

		showMyErrors: function(prefix, data) {
		  $$("label").each(function(lbl){ErrorHandler.clearErrorsIfAny(lbl);});
			for (intd = 0; intd < data.length; intd++) {
				var recreatedId = ErrorHandler.recreateCakeLabelId(prefix, data[intd].field);
				var inpt = $(recreatedId);
				var label = inpt.previous('label');
				ErrorHandler.clearErrorsIfAny(label);
				var newErr = document.createElement("span");
				newErr.className = "error";
				newErr.appendChild(document.createTextNode(data[intd].msg));
				label.appendChild(newErr);
				label.up('.field').addClassName('error');
			}
		},

		clearErrorsIfAny: function(l) {
			var sp = l.select('span');
			l.up().removeClassName('error');
			if (sp[0]) sp[0].remove();
		}

}