function ec_pop(page) {
	window.open(page,'popwin','resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,width=640,height=600');
};

function downloadWindow(link) {
	windowHandle = window.open('/store/checkout/download/item/'+link,'pop','scrollbars=no,resizable=no,width=600,height=250,top=100,left=100');
}

function imgpop(popimg){

	windowHandle = window.open('','pop','scrollbars=no,resizable=yes,width=1,height=1,top=10,left=10');
	var tmp = windowHandle.document;
	tmp.writeln('<html><head><title>Product Detail Image</title>');
	tmp.writeln('<scr'+'ipt language="javas'+'cript">');
	tmp.writeln('var picUrl = "'+popimg+'";');
	tmp.writeln('var NS = (navigator.appName=="Netscape")?true:false;');
	tmp.writeln('function FitPic() {');
	tmp.writeln('   wWidth = (NS)?window.innerWidth:document.body.clientWidth;');
	tmp.writeln('   wHeight = (NS)?window.innerHeight:document.body.clientHeight;');
	tmp.writeln('   iWidth = (document.images[0].width);');
	tmp.writeln('   iHeight = (document.images[0].height);');
	tmp.writeln('   window.resizeTo(iWidth+10, iHeight+20);');
	//tmp.writeln('   alert(iWidth+\' X \'+iHeight);');
	tmp.writeln('   self.focus();');
	tmp.writeln(' };');
	tmp.writeln('</scr'+'ipt>');
	tmp.writeln('</head>\n<body onload="FitPic();" style="background: url('+popimg+') no-repeat; background-color:#EEEEEE; margin:0px; padding:0px">');
	tmp.writeln('<img src="'+popimg+'" border="0" />');
	tmp.writeln('</body></html>');
	tmp.close();
	windowHandle.focus();
};


function checkRequired(form, message){
	var valid = true;
	// loop through all the elements on the form
	if (form.requiredfields){
	 textState = YAHOO.util.Dom.get('usingTextState');
		if (form.requiredfields.value.length){
			var rFields = form.requiredfields.value.split(":");
			for (i=0; i<rFields.length; i++) {
				if (form.elements[rFields[i]]) {
					try {
						var el = document.getElementById(rFields[i]);
						if (rFields[i] == 'StateText' && !document.getElementById('sameShip').checked) {
							continue;
						}

						if(rFields[i] == 'StateText' && textState['State'] == false){
							continue;
						}

						// check that required checkboxes are checked
						if (el.type == 'checkbox') {
							if (!el.checked) {
								YAHOO.util.Dom.replaceClass(el, 'txt-def', 'txt-req');
								valid = false;
							}
						} else {
							// all other elements
							if (el.value == '' || el.length == 0) {
								YAHOO.util.Dom.replaceClass(el, 'txt-def', 'txt-req');
								if (valid) {
									// set focus on first missing element
									el.focus();
								}
								valid = false;
							}else{
								if (YAHOO.util.Dom.hasClass(el, 'txt-req')) {
									YAHOO.util.Dom.replaceClass(el, 'txt-req', 'txt-def');
								}
							}
						}
					} catch (e) {
						// ignore
					}
				}
			}
		}
	}
	if (!valid) {
		if (message) {
			alert (message);
		} else {
			alert ("Please make sure all required fields are completed.");
		}
		return false;
	} else {
		return true;
	}
};


function checkMatch(first, second, alertText) {
	if (document.getElementById(first).value == document.getElementById(second).value) {
		return true;
	} else {
		document.getElementById(second).focus();
		alert (alertText);
		return false;
	}
}

function leaveccNumbers(formfield) {
	var newstring = "";
	var valid = "0123456789";
	var j = formfield.value.length;
	var formvalue = formfield.value;
	for(var i=0;i<j;i++){
		temp = formvalue.substring(i,i+1);
		if (valid.indexOf(temp)!=-1){
			newstring = newstring + temp;
		}
	}
	formfield.value = newstring;
	if (ccCheck(formfield)){
		return true;
	}else{
		alert("Please check your credit card number and make sure it is valid.");
		return false;
	}
}

function ccCheck(formfield) {
	var ccLen = formfield.value.length;
	if (ccLen == 16 && formfield.value.substr(0,1) == "5"){
		return true;
	}else if (ccLen == 15 && (formfield.value.substr(0,2) == "36" || formfield.value.substr(0,2) == "37")){
		return true;
	}else if ((ccLen == 13 || ccLen == 16) && formfield.value.substr(0,1) == "4" ){
		return true;
	}else if (ccLen == 16 &&  formfield.value.substr(0,4) == "6011" ){
		return true;
	}else{
		return false;
	}
}

function smartStateChange(countryField, stateField) {
	var country = document.getElementById(countryField);
	if (states[country.value]) {
		// change text to state
		if (usingTextState[stateField]) {
			textField = document.getElementById(stateField+'Text');
			textField.setAttribute('name',stateField+'Old');
			textField.style.visibility = 'hidden';
			textField.style.display = 'none';

			sel = document.getElementById(stateField+'Sel');
			sel.setAttribute('name',stateField);
			sel.style.visibility = 'visible';
			sel.style.display = 'block';
			sel.focus();

			usingTextState[stateField] = false;
		}

		// populate state with current countries states
		var state = document.getElementById(stateField+'Sel');
		// first clear
		for(i=state.options.length-1;i>=0;i--) {
			state.remove(i);
		}
		// then populate
		counter = 0;
		for(keyVar in states[country.value]) {
			if (keyVar != 'Not Applicable') {
				state.options[counter] = new Option(states[country.value][keyVar], keyVar);
				counter++;
			}
		}

	} else {
		// change state select to a text box
		if (!usingTextState[stateField]) {
			textField = document.getElementById(stateField+'Text');
			sel = document.getElementById(stateField+'Sel');
			sel.setAttribute('name',stateField+'Old');
			sel.style.visibility = 'hidden';
			sel.style.display = 'none';
			textField.setAttribute('name',stateField);
			textField.style.visibility = 'visible';
			textField.style.display = 'block';
			textField.focus();
			usingTextState[stateField] = true;
		}

	}
}


// price and quantity display
YAHOO.util.Event.onDOMReady(init);

function init(){
	try {
		renderer = new YAHOO.Product.Renderer();
		renderer.Render();
		kitRenderer = new YAHOO.Kits.Renderer();
		kitRenderer.Render();
	} catch(err) {
		return;
	}
};

function addProductOnChange(e,myObject){
	myObject.setAttributeValue(this);
};

function addProductOnFocus(e,myObject){
	myObject.loadAttributeValues(this);
	myObject.resetLowerSelects(this);
};
function focusAttribute(e,myObject){
	this.focus();
};


function itemExistsInString(itemName,regEx){
	//match all 7 digit numbers (note how "\d" is defined as "\\d")
		var itemSearch =new RegExp(regEx, "g");
		itemArray = itemSearch.exec(itemName);
		if(YAHOO.lang.isNull(items)){
			return false;
		}else{
			return itemArray;
		}
};

function setCurrentSelection(element,option){

	for(var index = 0; index < element.options.length; index++){
		if(element.options[index].value == option){
			element.selectedIndex = index;
			return;
		}
	}
};

function formatCurrency(num) {
		num = num.toString().replace(/\$|\,/g,'');
		if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
		if(cents<10)
		cents = "0" + cents;
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
		
		if(document.getElementById('currencySymbol')) {
			currencySymbol = document.getElementById('currencySymbol').value;
		} else {
			currencySymbol = '$';
		}
		return (((sign)?'':'-') + currencySymbol + '  ' + num + '.' + cents);
};


//clean the dropdown box and set initial selected Item
function  cleanDropDown(element,Name){
	if(YAHOO.lang.isNull(Name) || YAHOO.lang.isUndefined(Name)){
		Name = element.name;
	}
	// i;
	try{
		for(i=element.options.length-1;i>=0;i--){
		 element.remove(i);
		}
	}catch(err){

	}
	try{
		element.options[0] = new Option('-- Select ' + Name + ' --',0);
	}catch(Err){

	}

};

// on submit we will set the appropriate information to send to cart
function formCheck(myForm){

	renderer = new YAHOO.Product.Renderer();
	kitRenderer = new YAHOO.Kits.Renderer();

	var returnObject = new Object;
	returnObject.message = '';
	returnObject.status = true;

	var returnKitObject = new Object;
	returnKitObject.message = '';
	returnKitObject.status = true;


	var returnObject = renderer.CheckSubmit();
	var status = returnObject.status;
	var returnKitObject = kitRenderer.CheckSubmit();
	var kitStatus = returnKitObject.status;

	if(status == false || kitStatus == false){
		if(!YAHOO.lang.isNull(returnObject.message) && !YAHOO.lang.isUndefined(returnObject.message)){
			alert(returnObject.message);
			return false;
		}else if(!YAHOO.lang.isNull(returnKitObject.message) && !YAHOO.lang.isUndefined(returnKitObject.message)){
			alert(returnKitObject.message);
			return false;
		}
		return false;

	}

	return (status && kitStatus && true);

};

function resetQty(qtySelect,availableQty,Name){
	 cleanDropDown(qtySelect,Name);
	 if(YAHOO.lang.isNull(availableQty) || YAHOO.lang.isUndefined(availableQty)){
		return;
	 }
	try{
		for( index = 1; index <= availableQty; index++){
			if(index <= 30){
				qtySelect.options[index] = new Option(index,index);
			}
		}
		qtySelect.options[1].selected=true;
	}catch(err){
		//cleanDropDown(qtySelect, 'Product is Unavailable');
		qtySelect.options[0].selected=true;
	}
};

function createNamedElement(type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
	  element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
   }
   if (!element || element.nodeName != type.toUpperCase()) {
	  // Non-IE browser; use canonical method to create named element
	  element = document.createElement(type);
	  element.name = name;
   }
   return element;
}

/***************************************  product setup **********************/
// js functions for ecommerce
YAHOO.namespace("Kits");
YAHOO.namespace("Product");
expressCheckout = false;
/*************************  start set up classes **********************/
/*************************  end set up classes **********************/
var AttributeObject  = {
		attributeSelectedArray : new Array,
		objects : new Array
};
var AttributeKitObject  = {
		attributeSelectedArray : new Array,
		objects : new Array,
		idKey: 1
};


YAHOO.Product.LoadProducts = function(configArray) {

	if(YAHOO.lang.isNull(configArray.MatrixSize) || configArray.MatrixSize == 0 ){
		AttributeObject.objects.push(new YAHOO.Product.NonConfigurable(configArray));

	}else{
		AttributeObject.objects.push(new YAHOO.Product.Configurable(configArray));
	}


};

YAHOO.Kits.LoadProducts = function(configArray,baseObject) {
	//only add objects that are configurable
	if(!YAHOO.lang.isNull(configArray.MatrixSize) && configArray.MatrixSize != 0 ){
		AttributeKitObject.objects.push(new YAHOO.Kits.Configurable(configArray, baseObject, AttributeKitObject.idKey));
		AttributeKitObject.idKey++;
	}
};

//******************************   set up rendering function ***********/
YAHOO.Product.Renderer = function(){
	this.name = 'renderer';
};

YAHOO.Product.Renderer.prototype.Render= function(){

	for(var index in AttributeObject.objects){
		AttributeObject.objects[index].render();
	}

};

YAHOO.Product.Renderer.prototype.CheckSubmit = function(){
	returnObject = new Object;
	returnObject.message = null;
	returnObject.status = true;
	productReturnObject = new Object;

	for(var index in AttributeObject.objects){

		productReturnObject = AttributeObject.objects[index].checkSubmit();
	
		if(productReturnObject.status == false){
			returnObject = productReturnObject;
			
		}
	}
	return returnObject;
}

// to display kits

YAHOO.Kits.Renderer = function(){
	this.name = 'kit_renderer';
};

YAHOO.Kits.Renderer.prototype.Render = function(){

	for(var index in AttributeKitObject.objects){
		AttributeKitObject.objects[index].render();
	}

};

YAHOO.Kits.Renderer.prototype.CheckSubmit = function(){
	returnObject = new Object;
	returnObject.message = null;
	returnObject.status = true;
	kitReturnObject = new Object;

	for(var index in AttributeKitObject.objects){
		kitReturnObject = AttributeKitObject.objects[index].checkSubmit();
		if(kitReturnObject.status == false){
			returnObject = kitReturnObject;
		}
	}


	return returnObject;
};

//******************* Non configurable item class *******************/
YAHOO.Product.NonConfigurable= function(configArray) {
		this.id = 'nonconfigurable';
		this.config  = configArray;
		this.idKey = 'nonselect';

};
YAHOO.Product.NonConfigurable.prototype.checkSubmit= function() {
	returnObject = new Object;
	returnObject.message = null;
	returnObject.status = true;

	return returnObject;
}
YAHOO.Product.NonConfigurable.prototype.render = function() {
		qty = 0;
		var element = YAHOO.util.Dom.get('attributesForms');
		var qtySelect	= document.createElement('select');
		qtySelect.setAttribute('id','qty');
		qtySelect.setAttribute('name','qty');
		YAHOO.util.Dom.addClass(qtySelect,'dd-def');
		if (!expressCheckout) {
			var rowId = this.appendLabelTdToTable(qtySelect, element ,'Quantity');
		}


		var productPriceElement = YAHOO.util.Dom.get('productPrice');

		this.setPriceDetail(productPriceElement);

		if(YAHOO.lang.isNull(this.config.ProductRelationShips)){
			this.removeSubmit = true;
			qty = 0;
		}else{
			//pop an object off the relationship stack
			for(index in this.config.ProductRelationShips){
				//get relationship data
				relationShipObject = this.config.ProductRelationShips[index];
			}
			qty = relationShipObject.QuantityInReserve;
			if(qty > 5){
				qty = 5;
			}

			if(qty == 0){
				this.removeSubmit = true;
			}



		}

		if(this.config.Download == 1 || this.config.isSubscription == 1){
			this.removeSubmit = false;
			qty = 5;
		}
		/*if(this.config.AllowPreSale == 1){
			this.removeSubmit = false;
			qty = relationShipObject.QuantityPreSale;
			if(qty > 5){
				qty = 5;
			}
		}*/

		if(this.removeSubmit == true && !expressCheckout){
			//qtySelect.parentNode.removeChild(qtySelect);
			var item = YAHOO.util.Dom.get('submit');
			item.parentNode.removeChild(item);
			rowId.parentNode.removeChild(rowId);
			this.addTextLine(element,'This product is currently unavailable for purchase.');
			this.setPriceDetail(productPriceElement);
			return;

		}


		if(this.config.Download == 1 || this.config.isSubscription == 1){
			rowId.parentNode.removeChild(rowId);
		}else{
			resetQty(qtySelect,qty,'Quantity');
		}
		this.appendSubmitTdToTable(element);
		var productKey = YAHOO.util.Dom.get('key');
		if(!YAHOO.lang.isNull(this.config.CurrentProductKey)){
			productKey.value = this.config.CurrentProductKey;
		}else{
			productKey.value = 0;
		}

};

YAHOO.Product.NonConfigurable.prototype.appendLabelTdToTable = function(item,element,Name){

	if(YAHOO.lang.isNull(Name) || YAHOO.lang.isUndefined(Name)){
		Name = item.id;
	}

	// Insert a row in the table at row index 0
	var outerTr   = element.insertRow(-1);
	var attributeLabelTd  = outerTr.insertCell(0);
	var attributeValueTd  = outerTr.insertCell(1);
	strong1 = document.createElement("strong");
	txtno = document.createTextNode(Name +':');
	strong1.appendChild(txtno);
	attributeLabelTd.appendChild(strong1);
	attributeValueTd.appendChild(item);

	YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');
	YAHOO.util.Dom.addClass(item,'dd-def');
	YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');

	return outerTr;

};

YAHOO.Product.NonConfigurable.prototype.appendSubmitTdToTable = function(element){

	if (!expressCheckout) {
		var item 				= YAHOO.util.Dom.get('submit');
		var outerTr   = element.insertRow(-1);
		var attributeLabelTd  = outerTr.insertCell(0);
		var attributeValueTd  = outerTr.insertCell(1);
		YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');
		YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');

		//attributeLabelTd.appendChild(strong1);
		attributeValueTd.appendChild(item);
		return outerTr;
	}
};

YAHOO.Product.NonConfigurable.prototype.setPriceDetail = function(priceElement){

	if(this.config.SavingPercentage > 0){
		var hintElements = YAHOO.util.Dom.getElementsByClassName('hintprice', 'span');
		hintElement = hintElements.pop();
		hintElement.innerHTML = '  Save ' +this.config.SavingPercentage + '%';
	}


};

YAHOO.Product.NonConfigurable.prototype.addTextLine = function(element,itemName){

	strongTd  = document.createElement('strong');
	nameText = document.createTextNode(itemName);
	strongTd.appendChild(nameText);
	var outerTr   			= element.insertRow(-1);
	var innerTd  			= outerTr.insertCell(0);
	var outerTd  			= outerTr.insertCell(1);
	outerTd.setAttribute('colspan','2');
	YAHOO.util.Dom.addClass(outerTd,'ec-td-header ec-td-topborder');
	outerTd.appendChild(strongTd);
	return outerTr;
};

//***************************** configurable constructor and render class *******************//
YAHOO.Product.Configurable = function(configObject, returnProductKey) {
		this.id = 'configurable';
		this.config  = configObject;
		this.attributeSelectedArray = new Array;
		this.idKey = 'select';

};
YAHOO.Product.Configurable.prototype.checkSubmit= function() {
	returnObject = new Object;
	returnObject.message = '';
	returnObject.status = true;

	attributeSelectedCount = this.attributeSelectedArray.length;
	configurableItemCount = this.config.MatrixSize;

	 if(attributeSelectedCount < configurableItemCount  || this.config.checkOut == 0){
			try{
				productKeyElement = YAHOO.util.Dom.get('key');
				productKeyElement.value = 0;
			}catch(error){
				returnObject.status= false;
				returnObject.message ='Please Make a Selection';
				return returnObject;
			}
			returnObject.status= false;
			returnObject.message ='Please Make a Selection';
		  return returnObject;
	 }
	 else{
	   return returnObject;
	 }
	returnObject.status = false;
	return returnObject;
}
YAHOO.Product.Configurable.prototype.render = function() {
	element = YAHOO.util.Dom.get('attributesForms');

	this.rebuildSelects(element);
	this.productInit();
	/*basePrice       = eval(this.config.BasePrice);
	crossedPrice       = eval(this.config.CrossedPrice);
	displayMoney    =  formatCurrency(basePrice);
	//set the price default price back to base price
	productPriceElement = YAHOO.util.Dom.get('productPrice');
	priceStrong = productPriceElement.firstChild;
	priceStrong.innerHTML =  displayMoney;
	temp =  this.config.SavingPercentage;
	if(!YAHOO.lang.isNull(crossedPrice)){
		console.log('here');
		this.config.SavingPercentage =parseInt( ((crossedPrice - basePrice)/crossedPrice) * 100);
		this.setPriceDetail(productPriceElement);
	}*/
};


//****************************** class functions ***********************//
YAHOO.Product.Configurable.prototype.productInit = function(){
	try{
		if(this.config.ReturnProductKey > 0){
			this.loadInitProductInfo(this.config.ReturnProductKey);
		}
	}catch(err){
		return false;
	}
};

YAHOO.Product.Configurable.prototype.loadInitKitProductInfo = function(ReturnProductKey){

	//find product
	//for each select box on page
	var productKeyElement = YAHOO.util.Dom.get('key');
	productKeyElement.value = ReturnProductKey;
	for (var item in  this.config.Matrix){
		 selectId = AttributeObject.config.Matrix[item].Name + this.idKey;
		element 	= YAHOO.util.Dom.get(selectId);
		this.loadAttributeValues(element);
		attributes = this.getAttributesAllowed(selectId,new Array(ReturnProductKey));
		attribute = attributes.pop();
		this.setCurrentSelection(element,attribute);
		this.setAttributeValue(element);

	}
};

YAHOO.Product.Configurable.prototype.rebuildSelects = function(element){

	try{
		var setItem = new Array;
		var qtySelect	= document.createElement('select');
		qtySelect.setAttribute('id','qty');
		qtySelect.setAttribute('name','qty');

		var productPriceElement = YAHOO.util.Dom.get('productPrice');
		if(this.checkNoQuantity() == false){
			if(this.config.Download == 1 || this.config.isSubscription == 1){
				qty = 5;
			/*}else if(this.config.AllowPreSale == 1){
				qty = relationShipObject.QuantityPreSale;
				if(qty > 5){
					qty = 5;
				}
			*/
			}else{
				var submitRowId = this.appendSubmitTdToTable(element);
				submitRowId.parentNode.removeChild(submitRowId);
				this.addTextLine(element,'This product is currently unavailable for purchase.');
				return;
			}
		}

		for( var myMatrix in this.config.Matrix){

			 myItem = this.config.Matrix[myMatrix];

			var outerTr   = element.insertRow(-1);
			var attributeLabelTd  = outerTr.insertCell(0);
			var attributeValueTd  = outerTr.insertCell(1);

			YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');
			YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');

			strong1 = document.createElement("strong");
			txtno = document.createTextNode(myItem.Name+':');
			strong1.appendChild(txtno);
			attributeLabelTd.appendChild(strong1);

			// create select, add listeners and style, and then fill atributes
			var mySelect 		= document.createElement('select');
			YAHOO.util.Dom.addClass(mySelect,'dd-def');
			YAHOO.util.Event.addListener(mySelect,"change", addProductOnChange,this);
			mySelect.setAttribute('id', myItem.Name + this.idKey);
			mySelect.setAttribute('name', myItem.Name);
			mySelect.options[0] = new Option('-- Select ' + myItem.Name + ' --',0);
			mySelect.selectedIndex = 0;

			//add select to table
			attributeValueTd.appendChild(mySelect);
			this.loadAttributeValues(mySelect,qtySelect);

			if(mySelect.selectedIndex == 1){
					setItem.push(mySelect);
			}
		}

		if(this.config.Download != 1 && this.config.isSubscription != 1){
			this.appendLabelTdToTable(qtySelect,element,'Quantity');
		}
		this.appendSubmitTdToTable(element);

		for(var item in setItem){
			currentSelect= setItem[item];
			this.setAttributeValue(currentSelect);
			currentSelect.setAttribute('disabled','true');
		}

	}catch(err){

	}
};

//onFocus load the attributes box
YAHOO.Product.Configurable.prototype.loadAttributeValues= function(element,qtySelect){

	if(YAHOO.lang.isNull(qtySelect) || YAHOO.lang.isUndefined(qtySelect)){
			qtySelect = YAHOO.util.Dom.get('qty');
		}
	configArray =  this.config;
	productKeyArray = this.getPreviousAttributeAllowedProducts(element);
	attributesArray =  this.getAttributesAllowed(element.id,productKeyArray);
	if(this.config.Download != 1 && this.config.isSubscription != 1){
		cleanDropDown(element);
		cleanDropDown(qtySelect,'Quantity');
	}
	try{
		for(var item in configArray.Products) {
			   if((configArray.Products[item].Name + this.idKey) == element.id){
					selectIndex = element.selectedIndex;
					var count = 1;

					for(var index1 =0; index1 < attributesArray.length; index1++){
					   myItemValues = configArray.Products[item].Values;
					   for(var valueObject in myItemValues) {
							if(attributesArray[index1] == myItemValues[valueObject].Key && attributesArray[index1] != 0){
								var attributeQty = this.checkAttributeQuantity(myItemValues[valueObject].Key);
								if(attributeQty > 0){
									element.options[count] = new Option(myItemValues[valueObject].Value,myItemValues[valueObject].Key);
									count++;
								}
							  }
					   }
				   }
				   if(count == 2){
						element.selectedIndex = 1;
				   }else{
					element.selectedIndex = selectIndex;
					}
				}

		}
	}catch(err){
		return;
	}

};

// get element information of the next element in line
YAHOO.Product.Configurable.prototype.getNextBox = function(element){
	currentOrder = this.findOrder(element);

	currentOrder++;
	count = 0;
	for(var index in this.config.Matrix){
		if( currentOrder == count){
			return YAHOO.util.Dom.get(this.config.Matrix[index].Name + this.idKey);

		}
		count++;
	}
};

// find the order number of the current Item
YAHOO.Product.Configurable.prototype.findOrder = function(element){
	count = 0;
	for(var index in this.config.Matrix){
		if(element.id == this.config.Matrix[index].Name + this.idKey){
			return count;
		}
		count++;
	}
   return count;
};

// get all productKeys for a given element
YAHOO.Product.Configurable.prototype.getProductKeysAllowed = function (selectId, attributeValue){
	tempProductKeys = new Array;

	try{
	for (var att in this.config.Matrix){
	attributItem = this.config.Matrix[att];
	  if((attributItem.Name  + this.idKey) == selectId){
	  if(attributeValue > 0){

			 for(productKey in attributItem.ProductKeys){
				if(attributeValue == attributItem.ProductKeys[productKey].AttributeKey){
					tempProductKeys.push(attributItem.ProductKeys[productKey].ProductKey);
				}
			 }
		}
	  }
	}
   return tempProductKeys;
   }catch(err){
   return tempProductKeys;
   }
};

// get all attributes for a given array of productKeys
YAHOO.Product.Configurable.prototype.getAttributesAllowed = function(selectId,productKeyArray){
	var tempAttributes = new Array;

   try{
	for(var att in this.config.Matrix){
	 myMatrix = this.config.Matrix[att];
	  if((myMatrix.Name + this.idKey) == selectId){
		if(productKeyArray.length > 0){
			   for(var productKey in myMatrix.ProductKeys){
				  var myMatrixKeys = myMatrix.ProductKeys[productKey];
				  for(var index = 0; index < productKeyArray.length; index++){
					  if(productKeyArray[index] == myMatrixKeys.ProductKey){
						if(!YAHOO.util.Lang.isUndefined(myMatrixKeys.AttributeKey)){
							//check qty
							//
							tempAttributes[myMatrixKeys.AttributeKey] = myMatrixKeys.AttributeKey;
						}
					  }
				  }
			   }
		  }
		}
	}
   return tempAttributes;
   }catch(err){
   return tempAttributes;
   }
};

// on user selection add this selected itme to global javascript object
// and then clean the next attributes in line;
YAHOO.Product.Configurable.prototype.setAttributeValue = function(element){
	if(element == null){
		element = this;
	}
	this.addAttributesSelected(element);
	var selectionsNeeded = this.config.MatrixSize;

	if(this.attributeSelectedArray.length == selectionsNeeded){
		this.setProductProperties();
		this.config.checkOut == 1;
	} else {
		this.config.checkOut == 0;
	}
	try{
		currentOrder = this.findOrder(element);
		count = 0;
		for(var index in this.config.Matrix){
			if(count >  currentOrder){
				var nextBox = this.getNextBox(element);
				attribute = nextBox;
				cleanDropDown(nextBox);
				this.loadAttributeValues(nextBox);
				if(nextBox.selectedIndex == 1){
					this.setAttributeValue(nextBox);
					nextBox.setAttribute('disabled','true');
				}else{
					nextBox.removeAttribute('disabled');
				}
			}
			count++;
		}
	}catch(err){
		// do nothing
	}

 };


YAHOO.Product.Configurable.prototype.addAttributesSelected = function(attribute){


		currentOrder = this.findOrder(attribute);

		this.cleanAttributesSelected(attribute,currentOrder);
		itemObject = new Object;
		itemObject.attributeId = attribute.id;
		itemObject.attributePlace = currentOrder;

		itemObject.attributeSelectedValue = attribute.options[attribute.selectedIndex].value;
		itemObject.productKeysAllowed = this.getProductKeysAllowed(attribute.id,attribute.value);
		selectionsNeeded = this.config.MatrixSize;

		tempArray = new Array;
		duplicateFlag = 0;
		this.attributeSelectedArray.push(itemObject);
		for (var s in this.attributeSelectedArray){
			tempArray.push(this.attributeSelectedArray[s]);
			if(this.attributeSelectedArray[s].attributeId == itemObject.attributeId){
				tempArray.pop();
				if(duplicateFlag < 1){
					if(itemObject.attributeSelectedValue != 0){ //not the = to Please Select
					 tempArray.push(itemObject);
					}
				 }
				duplicateFlag++;
			 }
		}
	this.attributeSelectedArray= tempArray;
	if(this.attributeSelectedArray.length < selectionsNeeded){
		productKey = YAHOO.util.Dom.get('key');
		productKey.value = '0';
	}
};

// get all productKeys for a given element
YAHOO.Product.Configurable.prototype.getProductKeysAllowed = function(selectId, attributeValue){
	tempProductKeys = new Array;

	try{
		for (var att in this.config.Matrix){
		var attributItem = this.config.Matrix[att];
		  if((attributItem.Name + this.idKey) == selectId){
		  if(attributeValue > 0){

				 for(productKey in attributItem.ProductKeys){
					if(attributeValue == attributItem.ProductKeys[productKey].AttributeKey){
						for(var relationship in this.config.ProductRelationShips){
							myProduct = this.config.ProductRelationShips[relationship];
							if(attributItem.ProductKeys[productKey].ProductKey == myProduct.Key){
								if(myProduct.QuantityInReserve > 0){
									tempProductKeys.push(attributItem.ProductKeys[productKey].ProductKey);
								/*}else if(this.config.AllowPreSale == 1){
									if(myProduct.QuantityPreSale > 0){
										tempProductKeys.push(attributItem.ProductKeys[productKey].ProductKey);
									}*/
								}
							}
						}
					}
				 }
			}
		  }
		}
		return tempProductKeys;
   }catch(err){
   return tempProductKeys;
   }
};

YAHOO.Product.Configurable.prototype.cleanAttributesSelected = function(attribute,currentOrder){
	 cleanArray = new Array;
	if(currentOrder == 0){
	   this.attributeSelectedArray = new Array;
	}
	for(var s in this.attributeSelectedArray){
		if(this.attributeSelectedArray[s].attributePlace <= currentOrder){
			cleanArray.push(this.attributeSelectedArray[s]);
		}
	}

	this.attributeSelectedArray = cleanArray;
};
// get the previously selected option out of the global variable AttributeObject
YAHOO.Product.Configurable.prototype.getPreviousAttributeAllowedProducts = function(element){
	attributePlace = this.findOrder(element);
	 productKeyArray = new Array;
	if(this.attributeSelectedArray.length > 0 && attributePlace != 0){
		for (var item in this.attributeSelectedArray){
			if(attributePlace > this.attributeSelectedArray[item].attributePlace){
				return this.attributeSelectedArray[item].productKeysAllowed;
			   // return productKeyArray;
			}
		}
	}else if(attributePlace == 0){

			for ( var att in this.config.Matrix){
				if((this.config.Matrix[att].Name + this.idKey) == element.id){
				ProductKeys = this.config.Matrix[att].ProductKeys;
					for (var productKey in ProductKeys){
							productKeyArray.push(ProductKeys[productKey].ProductKey);
					   }
				}
			}
			return productKeyArray;
	}
};

YAHOO.Product.Configurable.prototype.appendLabelTdToTable = function(item,element,Name){

		if(Name == undefined){
			Name = item.id;
		}
		YAHOO.util.Dom.addClass(item,'dd-def');

		strong1 = document.createElement("strong");
		txtno = document.createTextNode(Name +':');
		strong1.appendChild(txtno);

		var outerTr   = element.insertRow(-1);
		var attributeLabelTd  = outerTr.insertCell(0);
		var attributeValueTd  = outerTr.insertCell(1);
		YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');
		YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');
		attributeLabelTd.appendChild(strong1);

		attributeLabelTd.appendChild(strong1);
		attributeValueTd.appendChild(item);
		return outerTr;

};
YAHOO.Product.Configurable.prototype.prependLabelTdToTable = function(item,element,Name){

		if(Name == undefined){
			Name = item.id;
		}

		YAHOO.util.Dom.addClass(item,'dd-def');

		outerTr			= document.createElement('tr');
		attributeLabelTd	= document.createElement('td');

		YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');

		strong1 = document.createElement("strong");
		txtno = document.createTextNode(Name +':');
		strong1.appendChild(txtno);
		attributeLabelTd.appendChild(strong1);

		attributeValueTd	= document.createElement('td');
		attributeValueTd.className = 'ec-td-value';

		attributeValueTd.appendChild(item);
		outerTr.appendChild(attributeLabelTd);
		outerTr.appendChild(attributeValueTd);
		//outerTBody.appendChild(outerTr);
		firstChild = element.firstChild;
		element.insertBefore(outerTr,firstChild.nextSibling);


};

YAHOO.Product.Configurable.prototype.loadInitProductInfo = function(ReturnProductKey){
	//find product
	//for each select box on page
	 productKeyElement = YAHOO.util.Dom.get('key');
	productKeyElement.value = ReturnProductKey;
	for (var item in  this.config.Matrix){
		selectId = this.config.Matrix[item].Name + this.idKey;
		element 	= YAHOO.util.Dom.get(selectId);
		this.loadAttributeValues(element);
		attributes = this.getAttributesAllowed(selectId,new Array(ReturnProductKey));
		attribute = attributes.pop();
		setCurrentSelection(element,attribute);
		this.setAttributeValue(element);
	}
};

YAHOO.Product.Configurable.prototype.getProductKey = function(attributeArray){

	for (var item in  this.config.ProductRelationShips){
		var count = 0;
	var ProducRelationShipsItem = this.config.ProductRelationShips[item];
		for(var index = 0; index < ProducRelationShipsItem.Value.length; index++){
			for(var index2 = 0; index2 < attributeArray.length; index2++){
				   if(ProducRelationShipsItem.Value[index] == attributeArray[index2]){
						count++
					}
			}
			if(count == this.config.MatrixSize){
					//return productKey;
					return ProducRelationShipsItem.Key;

			 }
		}
	}
};

YAHOO.Product.Configurable.prototype.setProductProperties = function(){
	 var productKeyElement = YAHOO.util.Dom.get('key');
	 var qtySelect 		   = YAHOO.util.Dom.get('qty');
	 var attributeArray = new Array;
	 for(var selectedObject in this.attributeSelectedArray){
			attributeArray.push(this.attributeSelectedArray[selectedObject].attributeSelectedValue);
	 }
	var productKey = this.getProductKey(attributeArray)
	attributeSelectedArray = this.attributeSelectedArray;
	var currentProductCount = this.attributeSelectedArray.length;
	var  configurableItemCount = eval(this.config.MatrixSize);
	for(var prod in this.config.ProductRelationShips){

			if(this.config.ProductRelationShips[prod].Key == productKey){
				var productKeyElement = YAHOO.util.Dom.get('key');
				var productPriceElement = YAHOO.util.Dom.get('productPrice');
				if(this.config.Download != 1 && this.config.isSubscription != 1){
					qty = this.config.ProductRelationShips[prod].QuantityInReserve;
					/*if(this.config.AllowPreSale == 1){
						qty = this.config.ProductRelationShips[prod].QuantityPreSale;
					}*/
					if(qty > 5){
						qty = 5;
					}

					resetQty(qtySelect,qty,'Quantity');
				}

				productKeyElement.setAttribute('value', productKey);
				basePrice       = eval(this.config.BasePrice);
				priceIncrease   = eval(this.config.ProductRelationShips[prod].PriceIncrease);
				newProductPrice =   basePrice + priceIncrease;
				displayMoney    =  formatCurrency(newProductPrice);
				crossedPrice    = eval(this.config.CrossedPrice);
				//if there is a crossed or old price we know then that there is a discount
				if(!YAHOO.lang.isNull(crossedPrice)){
				   this.config.SavingPercentage =parseInt( ((crossedPrice - newProductPrice)/crossedPrice) * 100);
				   this.setPriceDetail(productPriceElement);
				}
				 var priceStrong = productPriceElement.firstChild;
				 priceStrong.innerHTML = displayMoney;
				 if(this.config.Download != 1 && this.config.isSubscription != 1){
					qtySelect.focus();
				 }
			}
		}
};

YAHOO.Product.Configurable.prototype.addTextLine = function(element,itemName){

	strongTd  = document.createElement('strong');
	nameText = document.createTextNode(itemName);
	strongTd.appendChild(nameText);
	var outerTr   			= element.insertRow(-1);
	var innerTd  			= outerTr.insertCell(0);
	var outerTd  			= outerTr.insertCell(1);
	//innerTd.setAttribute('colspan','2');
	YAHOO.util.Dom.addClass(outerTd ,'ec-td-header ec-td-topborder');
	outerTd .appendChild(strongTd);
	return outerTr;
};
YAHOO.Product.Configurable.prototype.appendSubmitTdToTable = function(element){

		if (!expressCheckout) {
			var item 				= YAHOO.util.Dom.get('submit');
			//YAHOO.util.Event.addListener(item,"click", formCheck);
			var outerTr   			= element.insertRow(-1);
			var attributeLabelTd  	= outerTr.insertCell(0);
			var attributeValueTd  	= outerTr.insertCell(1);
			YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');
			YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');
			attributeValueTd.appendChild(item);
			return outerTr;
		}
};

YAHOO.Product.Configurable.prototype.setPriceDetail = function(priceElement){

	if(this.config.SavingPercentage > 0){
		var hintElements = YAHOO.util.Dom.getElementsByClassName('hintprice', 'span');
		hintElement = hintElements.pop();
		hintElement.innerHTML = '  Save ' +this.config.SavingPercentage + '%';
	}


};

YAHOO.Product.Configurable.prototype.resetLowerSelects = function(element){
	try{
		 currentOrder = this.findOrder(element);
		 count = 0;
		for(var index in this.config.Matrix){
			if(count >  currentOrder){
				var nextBox = this.getNextBox(element);
				cleanDropDown(nextBox);
				nextBox.selectedIndex = 0;
				for(var item in this.attributeSelectedArray){
					//remove fromthe selected array
					if(this.attributeSelectedArray[item].attributeId == element.id  || this.attributeSelectedArray[item].attributeId == nextBox.id){
						this.attributeSelectedArray.splice(item,1);
					}
				}
			}
			count++;
		}
	 }catch(err){

	 }
};
YAHOO.Product.Configurable.prototype.checkNoQuantity = function(){
	var qty = 0;
	if(YAHOO.lang.isNull(this.config.ProductRelationShips)){
		return qty;
	}else{
		//pop an object off the relationship stack
		for(var index in this.config.ProductRelationShips){
			//get relationship data
			relationShipObject = this.config.ProductRelationShips[index];
			/*if(this.config.AllowPreSale == 1){
				qty = qty + relationShipObject.QuantityPreSale;
			}else{*/
				qty = qty + relationShipObject.QuantityInReserve;
			/*}*/
		}
		if(this.config.Download == 1 || this.config.isSubscription == 1){
			return 5;
		}
		return qty;
	}
};

YAHOO.Product.Configurable.prototype.checkAttributeQuantity = function(attributeKey){
	var qty = 0;
	if(YAHOO.lang.isNull(this.config.ProductRelationShips)){
		return qty;
	}else{
		//pop an object off the relationship stack
		for(var index in this.config.ProductRelationShips){
			//get relationship data
			for(var value in this.config.ProductRelationShips[index].Value){
				var currentKey = this.config.ProductRelationShips[index].Value[value];
				if(attributeKey == currentKey){
					relationShipObject = this.config.ProductRelationShips[index];
					/*if(this.config.AllowPreSale == 1){
						qty = qty + relationShipObject.QuantityPreSale;
					}else{*/
						qty = qty + relationShipObject.QuantityInReserve;
					/*}*/
				}
			}
		}
		if(this.config.Download == 1 || this.config.isSubscription == 1){
			return 5;
		}

		return qty;
	}
}


//*****************************  configurable kits ***********************//

YAHOO.Kits.Configurable = function(configObject,baseObject,idKey){
		this.id = 'kit_configurable';
		this.config  = configObject;
		this.baseConfig  = baseObject;
		this.attributeSelectedArray = new Array;
		this.idKey = idKey;
};
	// Class2 extends Class1.  Must be done immediately after the Class2 constructor
	YAHOO.lang.extend(YAHOO.Kits.Configurable, YAHOO.Product.Configurable);

	YAHOO.Kits.Configurable.prototype.checkSubmit= function() {
	returnObject = new Object;
	returnObject.status = false;
	returnObject.message = 'There is a least one item not configured';

	attributeSelectedCount = this.attributeSelectedArray.length;
	configurableItemCount = this.config.MatrixSize;
	seeme = YAHOO.util.Dom.getChildren('productKitItems');
	for( index in seeme){
		if(seeme[index].name == 'productKeys['+this.config.KitInfo.ChildContainerKey+ ']'){
			returnObject.status= true;
			returnObject.message = null;
			return returnObject;

		}
	}

	return returnObject;
};

YAHOO.Kits.Configurable.prototype.rebuildSelects = function(element){
	try{
		var setItem = new Array;
		var qtySelect = YAHOO.util.Dom.get('qty');
		var productPriceElement = YAHOO.util.Dom.get('productPrice');
		this.setPriceDetail(productPriceElement);
		var qty = this.checkNoQuantity();
		if(qty == 0){
			return;
		}

		this.addTextLine(element,this.config.ContainerProductName);

		for(var myMatrix in this.config.Matrix){
			var myItem = this.config.Matrix[myMatrix];
			var outerTr   = element.insertRow(-1);
			var attributeLabelTd  = outerTr.insertCell(0);
			var attributeValueTd  = outerTr.insertCell(1);
			YAHOO.util.Dom.addClass(attributeLabelTd,'ec-td-label');
			YAHOO.util.Dom.addClass(attributeValueTd,'ec-td-value');
			var strong1 = document.createElement("strong");
			var txtno = document.createTextNode(myItem.Name+':');
			strong1.appendChild(txtno);
			attributeLabelTd.appendChild(strong1);
			// create select, add listeners and style, and then fill atributes
			var mySelect 		= document.createElement('select');
			YAHOO.util.Dom.addClass(mySelect,'dd-def');
			YAHOO.util.Event.addListener(mySelect,"change", addProductOnChange,this);
			mySelect.setAttribute('id', myItem.Name + this.idKey);
			mySelect.setAttribute('name', myItem.Name);
			mySelect.options[0] = new Option('-- Select ' + myItem.Name + ' --',0);
			mySelect.selectedIndex = 0;
			//add select to table
			attributeValueTd.appendChild(mySelect);
			this.loadAttributeValues(mySelect,qtySelect);
			if(mySelect.selectedIndex == 1){
					setItem.push(mySelect);
			}
		}

		this.appendSubmitTdToTable(element);

		for(var item in setItem){
			this.setAttributeValue(setItem[item]);
			setItem[item].setAttribute('disabled','true');
		}

	}catch(err){
		return;
	}
};

YAHOO.Kits.Configurable.prototype.loadAttributeValues= function(element){
	configArray =  this.config;
	 productKeyArray = this.getPreviousAttributeAllowedProducts(element);
	 attributesArray =  this.getAttributesAllowed(element.id,productKeyArray);
	cleanDropDown(element);

	 for( var item in configArray.Products) {
		   if((configArray.Products[item].Name + this.idKey) == element.id){
				  selectIndex = element.selectedIndex;
			   if(element.tagName.toLowerCase() == 'select'){
						count = 1;
					for(var index1 =0; index1 < attributesArray.length; index1++){
					   var myItemValues = configArray.Products[item].Values;
					   for(var valueObject in myItemValues) {
								   if(attributesArray[index1] == myItemValues[valueObject].Key && attributesArray[index1] != 0){
									   element.options[count] = new Option(myItemValues[valueObject].Value,myItemValues[valueObject].Key);
									   count++;
									 }
					   }

				}
			}
			if(count == 2){
				element.selectedIndex = 1;
			}else{
				element.selectedIndex = selectIndex;
			}
			}
	}
};

YAHOO.Kits.Configurable.prototype.setProductProperties = function(){

	// need to add these items to the kitProductsArray
	 productKeyElement = YAHOO.util.Dom.get('productKitItems');
	attributeArray = new Array;
	for(selectedObject in this.attributeSelectedArray){
		attributeArray.push(this.attributeSelectedArray[selectedObject].attributeSelectedValue);
	}
	productKey = this.getProductKey(attributeArray)

	attributeSelectedArray = this.attributeSelectedArray;
	currentProductCount = this.attributeSelectedArray.length;
	configurableItemCount = eval(this.config.MatrixSize);
	for(var prod in this.config.ProductRelationShips){
		if(this.config.ProductRelationShips[prod].Key == productKey){
			hiddenNewProductItem = this.getProductKeyItem(productKeyElement);
			hiddenNewProductItem.setAttribute('name','productKeys['+this.config.KitInfo.ChildContainerKey+ ']');
			hiddenNewProductItem.setAttribute('value', productKey);
			productKeyElement.appendChild(hiddenNewProductItem);
			var productPriceElement = YAHOO.util.Dom.get('productPrice');
			var basePrice       = eval(this.config.BasePrice);
			var priceIncrease   = eval(this.config.KitInfo.ChildItemPrice);
			var newProductPrice =   this.baseConfig.BasePrice + priceIncrease;
			var displayMoney    =  formatCurrency(newProductPrice);
		}
	}
};

YAHOO.Kits.Configurable.prototype.searchProductKeys = function(productKeyArray,containerKey){
	regEx = '\['+containerKey+'\]';
	document.childNodes;
	for(index in productKeyArray){
		id = productKeyArray[index].id;
		if(itemExistsInString(id,regEx) == false){
			return false;
		}
	}
};

YAHOO.Kits.Configurable.prototype.getProductKeyItem = function(productKeyElement){
	for(index in productKeyElement.childNodes){
		if(!YAHOO.lang.isUndefined(productKeyElement.childNodes[index]) && productKeyElement.childNodes[index].name == 'productKeys['+this.config.KitInfo.ChildContainerKey+ ']'){
			//don't ask me why this works and productKeyElement.childNodes(productKeyElement.childNodes[index]) does not!!!!!
			productKeyElement.childNodes[index].parentNode.removeChild(productKeyElement.childNodes[index]);
		}
	}
	hiddenNewProductItem= document.createElement('input');
	hiddenNewProductItem.setAttribute('type','hidden');
	return hiddenNewProductItem;
};
