formBundle = "";

Product.FormBundle = Class.create(Product.Bundle,{
    reloadPrice: function() {
        var calculatedPrice = 0;
        var dispositionPrice = 0;
        for (var option in this.config.selected) {
            if (this.config.options[option]) {
                for (var i=0; i < this.config.selected[option].length; i++) {
                    var prices = this.selectionPrice(option, this.config.selected[option][i]);
                    calculatedPrice += Number(prices[0]);
                    dispositionPrice += Number(prices[1]);
                }
            }
        }
    
        formOptionsPrice.changePrice('bundle', calculatedPrice);
        formOptionsPrice.changePrice('nontaxable', dispositionPrice);
        formOptionsPrice.reload();
    
        return calculatedPrice;
    },
    
    selectionPrice: function(optionId, selectionId) {
        if (selectionId == '' || selectionId == 'none') {
            return 0;
        }

        if (this.config.options[optionId].selections[selectionId].customQty == 1 && !this.config['options'][optionId].isMulti) {
            if ($('bundle-option-' + optionId + '-instant-pricing-qty-input')) {
                qty = $('bundle-option-' + optionId + '-instant-pricing-qty-input').value;
            } else {
                qty = 1;
            }
        } else {
            qty = this.config.options[optionId].selections[selectionId].qty;
        }

        if (this.config.priceType == '0') {
            price = this.config.options[optionId].selections[selectionId].price;
            tierPrice = this.config.options[optionId].selections[selectionId].tierPrice;

            for (var i=0; i < tierPrice.length; i++) {
                if (Number(tierPrice[i].price_qty) <= qty) {
                    price = tierPrice[i].price;
                }
            }
        } else {
            selection = this.config.options[optionId].selections[selectionId];
            if (selection.priceType == '0') {
                price = selection.priceValue;
            } else {
                price = (this.config.basePrice*selection.priceValue)/100;
            }
        }

        
        var disposition = this.config.options[optionId].selections[selectionId].plusDisposition +
            this.config.options[optionId].selections[selectionId].minusDisposition;

        if (this.config.specialPrice) {
            newPrice = (price*this.config.specialPrice)/100;
            newPrice = (Math.round(newPrice*100)/100).toString();
            price = Math.min(newPrice, price);
        }
        var result = new Array(price*qty, disposition*qty);
        return result;
    },
    showQtyInput: function(optionId, value, canEdit) {
        elem = $('bundle-option-' + optionId + '-instant-pricing-qty-input');
        elem.value = value;
        elem.disabled = !canEdit;
        if (canEdit) {
            elem.removeClassName('qty-disabled');
        } else {
            elem.addClassName('qty-disabled');
        }
    }
});


function changeProduct() {
	catId = $F('product_selection');
	
	$('product_sizes').childElements().invoke('remove');

	$('product_sizes').insert("<option value=''  selected='selected'>Please make a size selection</option>");


	$H(products[catId]).findAll(function(pair){
		if(!Object.isFunction(products[catId][pair.key])) {
			$('product_sizes').insert("<option value='" + pair.key + "'>" + pair.value + "</option>");
		}
	});

	$('option-holder').childElements().invoke('remove');

	changeSizes();
}

function changeSizes() {
	size = $F('product_sizes');
	formOptionsPrice = null;
	formBundle = null;

	if(!$('product-price-' + size)) {
	    $$("#fake_container .fake-price").each(function(fakeElm) {
	    	fakeElm.id = 'product-price-' + size; //hack fix
	    });
	} 
    
	new Ajax.Request('/instantpricing/index/product/id/' + size, {
		  onSuccess: function(transport) {
			  var json = transport.responseText.evalJSON();

			  if(json['product']['options']) {

                formOptionsPrice = new Product.OptionsPrice(json['price']);
                //TODO: add busy graphic if this takes too long
                
                $('qty_select').childElements().invoke('remove');
                $('option-holder').childElements().invoke('remove');

				if($$('.price-calculate .price')) {
    				$$('.price-calculate .price').each(function(elm) {
    					elm.id = 'product-price-' + size + '_form';
    				});
				}
				
			  	parseOptions(json['product']['options'],json['product'].selected);
			  	
                formBundle = new Product.FormBundle(json['product']);
                
                $$('select#qty_select option')[0].selected = true;	
                	  
                changeInstantPriceQty();
			  }
		  }
		});
}

function parseOptions(options,selectedOptions) {
	for(option in options) {
		var currOption = options[option];

		if(typeof currOption  == "object") { 
			if(currOption.isMulti == false) { //dropdown
				var htmlOption = "<dt><label for='bundle-option-" + option + "' id='bundle-option-" + option + "-label-instant-pricing'>" + currOption.title + "</label></dt><dd>";
				htmlOption += "<select onchange='changeSelection(this)' id='bundle-option-" + option + "-instant-pricing' name='bundle_option[" + option + "]' class='bundle-option-" + option + " bundle-option-select bundle-option'></select>";
				htmlOption += "<input class='price-qty' type='hidden' id='bundle-option-" + option + "-instant-pricing-qty-input'/></dd>";

				$('option-holder').insert(htmlOption);

				var selectionHtml = "<option value=''>";

				selectionHtml+= (currOption.title !="Color Options") ? "No " + currOption.title : "Choose a selection..."; 

				$$("#price_calculate #bundle-option-" + option + '-instant-pricing').each(function(elm) {
					elm.insert(selectionHtml + "</option>");
				});
				
				//$("bundle-option-" + option).insert(selectionHtml + "</option>");

				$$("#price_calculate #bundle-option-" + option + "-instant-pricing-qty-input").each(function(elm) {
					elm.setValue(1);
				});
				
				//$("bundle-option-" + option + "-qty-input").setValue(1);
				
				var selectList = currOption.selections;
				
				
				for(selectItem in selectList) {
					var useQty = false;

					if(currOption.title =="Color Options") {
						useQty = true;
					}

					$$("#price_calculate #bundle-option-" + option + '-instant-pricing').each(function(elm) {
						parseOption(selectList[selectItem], selectItem, elm,false, useQty);
					});
				}

    			if(selectedOptions[option]) {
    				$$('select#bundle-option-' + option + '-instant-pricing option').each(function(o){
  				      if(o.value==selectedOptions[option]){
  	  				      o.selected = true;
  	  				      $break;
  	  				  }
  					});
    			} else {
					$('bundle-option-' + option + '-instant-pricing')[0].selected=true;
        		}
				
			} else {
				//assume checkbox for now
				var html ="<dt><label id='bundle-option-" + option + "-label-instant-pricing'>" + currOption.title + "</label></dt><dd><ul class='options-list'>";
				
				var selectList = currOption.selections;
				
				for(selectItem in selectList) {
					html+=makeCheckBox(selectList[selectItem], selectItem, option);
				}

				html+= "</ul></dd>";

				$('option-holder').insert(html);
			}	

		} else {
			console.log(option + ": ", currOption);
		}
	}
}

function parseOption(option, key, elm, selected, useQty) {
	if(typeof option  == 'object') {
		var html = "<option value='" + key + "'";

		html+= (selected)  ? " selected='yes' " : "";

		html+=">" + option.name + "</option>";
		
		elm.insert(html);

		if(formOptionsPrice && formOptionsPrice.priceFormat && formOptionsPrice.priceFormat.precision && useQty) {
			getQtyFromTieredPricing(option.tierPrice,formOptionsPrice.priceFormat.precision, useQty);
		}
	} 
}


function makeCheckBox(option, key, optionId, useQty)
{
	var html = "";
	
	if(typeof option  == 'object') {
		
		html+="<li><input onchange='changeSelection(this)' type='checkbox' value='" + key + "' name='bundle_option["+optionId+"][]' id='bundle-option-"+ optionId+"-"+key + "-instant-pricing";
		
		html+="' class='checkbox bundle-option bundle-option-"+optionId+"'/><span class='label'><label for='bundle-option-"+optionId+"-"+key+"-instant-pricing' id='bundle-option-"+optionId+"-"+key+"-label-instant-pricing'>" + option.name + "</label></span></li>";

		if(useQty) {
			getQtyFromTieredPricing(option.tierPrice,0);
		}
	} 

	return html;
}

function getQtyFromTieredPricing(priceList, precision) {
	$('qty_select').childElements().invoke('remove');
	
//	for(priceList) { //	if(priceList.length > 0)
		

    	for(var priceObj in priceList) {
        	obj = priceList[priceObj];
        	
        	if(obj.price_qty) {
            	$('qty_select').insert("<option value='" + Math.round(obj.price_qty,precision) + "' >" + Math.round(obj.price_qty,precision) + "</option>");
        	}
    	}
	//}	
}

function changeInstantPriceQty() {
	//update qty
	$$('.price-calculate .price-qty').each(function(elm) {
		elm.value = $('qty_select').getValue();
	});

	//update price
	$$('.price-calculate .bundle-option').each(function(elm) {
			changeSelection(elm);
	});
}

function changeSelection(elm)
{
	formBundle.changeSelection(elm);
	optionId = elm.id.split('-');

	if(optionId.length>1) {
    	option =$('bundle-option-' + optionId[2] + '-instant-pricing-qty-input'); 
    
    	if(option) {
    		option.value = $('qty_select').getValue();
    	}
    }

	$('line_items').innerHTML = showLineItems();
	
	if(elm.getValue()!="") {
		formBundle.changeOptionQty(elm, false);
	}
}

function showLineItems()
{
	var bodyString = "";
	formValues = $('price_calculate').serialize(true);

		for(myVar in formValues) {
		    if(myVar!="contact_me" && myVar!="product_selection") {
		        if(myVar.indexOf("bundle_option")>=0) {
		            var option_id = myVar.replace(/[^0-9]+/gi,"");

					if($('bundle-option-' + option_id + '-' + formValues[myVar] + '-label')
							|| Object.isArray(formValues[myVar])) {
						if(Object.isArray(formValues[myVar])) {
							formValues[myVar].each(function(selectionId) {
								var coding = ""; //getCoding($('bundle-option-' + option_id + '-' +selectionId + '-label').innerHTML);
	    						var option_name = $('bundle-option-' + option_id + '-' +selectionId + '-label-instant-pricing').innerHTML;
	        					
	    						bodyString+="<li><span class='option-name'> " + option_name + "</span>" + formOptionsPrice.formatPrice(formBundle.selectionPrice(option_id,selectionId)[0]) + "<span class='coding'>" + coding + "</span></li>";
	    						
							});
						} else {
							var coding = ""; //getCoding($('bundle-option-' + option_id + '-' +formValues[myVar] + '-label').innerHTML);
    						var option_name = $('bundle-option-' + option_id + '-' +formValues[myVar] + '-label-instant-pricing').innerHTML;
    					
    						bodyString+="<li><span class='option-name'> " + option_name + "</span>" + formOptionsPrice.formatPrice(formBundle.selectionPrice(option_id,formValues[myVar])[0]) + "<span class='coding'>" + coding + "</span></li>";
						}
					} else if($('bundle-option-' + option_id + '-instant-pricing')) {
						var option_name = $('bundle-option-' + option_id + '-label-instant-pricing').innerHTML;

						var coding = "";
						if(option_name == "Color Options") {
							option_name = "Printing";
							
							coding = ""; //getCoding($('product_sizes')[$('product_sizes').selectedIndex].text);
						}

						if(formBundle.config.selected[option_id] && formBundle.config.selected[option_id][0]){
    						var selectionId = formBundle.config.selected[option_id][0];

    						if(coding=="") {
        						coding = ""; //getCoding($('bundle-option-' + option_id)[$('bundle-option-' + option_id).selectedIndex].text);
    						}
        					bodyString+="<li><span class='option-name'> " +  option_name + "</span>" + formOptionsPrice.formatPrice(formBundle.selectionPrice(option_id,selectionId)[0]) + "<span class='coding'>" + coding + "</span></li>";
						}
					}
			    }
		    }
		}

	return bodyString;
}


startofMailLink = "mailto:sales@tailormadeprinting.com?subject=" + encodeURIComponent("Quote Request");

function createQuote(elm) {
	elm.href=startofMailLink + "&body=" + encodeURIComponent(emailBodyForm());
}

function emailBodyForm(){
var bodyString = "";
formValues = $('price_calculate').serialize(true);

	for(myVar in formValues)
	{
	    if(myVar!="contact_me" && myVar!="product_selection") {
	        if(myVar.indexOf("bundle_option")>=0) {
	            var option_id = myVar.replace(/[^0-9]+/gi,"");
		
				if($('bundle-option-' + option_id + '-' + formValues[myVar] + '-instant-pricing')) {
					var option_name = $('bundle-option-' + option_id + '-' + 'label-instant-pricing').innerHTML;
					var option_value = $('bundle-option-' + option_id + '-' + formValues[myVar]+ '-label-instant-pricing').innerHTML;
				
					bodyString+=option_name + ': ' + option_value + "\n";
				} else if($('bundle-option-' + option_id + '-instant-pricing')) {
					var option_value = $('bundle-option-' + option_id + '-instant-pricing')[$('bundle-option-' + option_id + '-instant-pricing').selectedIndex].text;
					var option_name = $('bundle-option-' + option_id + '-' + 'label-instant-pricing').innerHTML;
					bodyString+=option_name + ': ' + option_value + "\n";
				}
	        } else {
	        	console.log(myVar);
			var option_value = $(myVar)[$(myVar).selectedIndex].text;
			var option_name = $(myVar + '-label-instant-pricing').innerHTML;
			bodyString+=option_name + ': ' + option_value + "\n";
	        }
	    }
	}

	var option_value = $('qty_select')[$('qty_select').selectedIndex].text;
	
	bodyString+='Quantity : ' + option_value + "\n";

	$$('.price-calculate .price').each(function(elm) {
		bodyString+='Price: ' + elm.innerHTML;
	});
	
	return bodyString;
}

function getCoding(string) {
	var firstPara = string.lastIndexOf('(');

	if(firstPara>=0) {
		return string.substr(firstPara);
	}

	return "";
}
