/**
* Global Variables
*/
var Quotes = new Array(), Steps = new Array(), Systems = new Array(), Lengths = new Array(), ShippingMethods = new Array(), Prices = new Array();
var BasePrice = 25;
var StepIndex = 1, SystemIndex = 1, LengthIndex = 1, PriceIndex = 1, ShippingMethodIndex = 1, UPSELL_COUNT = 0;
var SystemSelected=null, LengthSelected=null, PriceSelected=null, ShippingMethodSelected=null;
var SystemDefault = null,LengthDefault=null, PriceDefault=null, ShippingMethodDefault=null;

/**
* Prototype Class Definitions
*/

var Step = Class.create({
  initialize: function(step_number, label, title, description) {
    this.id = StepIndex;
    //this.template = new Template('<h4 class="step">#{label}&nbsp;#{title}</h4><p>#{description}</p>');
    this.template = new Template('<img src="#{image}" alt="#{label} #{title}" /><p>#{description}</p>');
	this.step_number = step_number;
	this.label = label;
	this.title = title;
	this.description = description;
	StepIndex++;
  },
  addElement: function() {
	$( 'step_' + this.step_number ).insert( {top: this.template.evaluate( {image: '../../../gui/images/calculator/layout/step_' + this.id + '.jpg', label: this.label, title: this.title, step_number: this.step_number, description: this.description} ) });
  }
});

/*
<system>
	<name>partial</name>
	<title>Partial Piece</title>
	<description>Top of head, anything smaller than 6x9</description>
	<price_modifier>0</price_modifier>
</system>
*/
var System = Class.create({
  initialize: function(name, title, description, email_description, price_modifier, selected) {
    this.id = SystemIndex;
	this.template = new Template('<dt><input id="system_#{id}" name="system" onclick="javascript: handleSystem(\'#{id}\');" value="#{name}" #{checked} type="radio" /><label for="system_#{id}">#{title}</label></dt><dd>#{description}</dd>');
	this.name = name;
	this.title = title;
	this.description = description;
	this.email_description = email_description;
	this.price_modifier = parseFloat(price_modifier);
	
	if( selected == "true" )
	{
		SystemSelected = SystemDefault = this.id;
	}
	SystemIndex++;
  },
  addElement: function() {
	$('system_list').insert( this.template.evaluate( {id: this.id, name: this.name, title: this.title, description: this.description, checked: (this.id == SystemSelected ? 'checked' : '')} ) );
  }
	  
});

/*
<length>
	<title>8 Inches</title>
	<partial_price_modifier>30</partial_price_modifier>
	<three_quarter_price_modifier>30</partial_price_modifier>
	<full_price_modifier>35</partial_price_modifier>
</length>
*/
var Length = Class.create({
    initialize: function(title, partial_price_modifier, three_quarter_price_modifier, full_price_modifier, selected) {
        this.id = LengthIndex;
        this.template = new Template('<div class="length"><input id="length_#{id}" name="length" value="#{title}" #{checked} onclick="javascript: LengthSelected = \'#{id}\';" type="radio" /><label for="length_#{id}">#{title}</label></td>');
        this.title = title;
        this.partial_price_modifier = parseFloat(partial_price_modifier);
        this.three_quarter_price_modifier = parseFloat(three_quarter_price_modifier);
        this.full_price_modifier = parseFloat(full_price_modifier);
        this.price_modifier = null;

        if (selected == "true") {
            LengthSelected = LengthDefault = this.id;
        }
        LengthIndex++;
    },
    addElement: function() {
        var boolAdd = false;
        switch (Systems[SystemSelected].name) {
            case 'partial':
                if (isNaN(this.partial_price_modifier)) { if (this.id == LengthSelected) { this.price_modifier = null; LengthSelected = null; } } else { this.price_modifier = this.partial_price_modifier; boolAdd = true; }
                break;
            case 'three_quarter':
                if (isNaN(this.three_quarter_price_modifier)) { if (this.id == LengthSelected) { this.price_modifier = null; LengthSelected = null; } } else { this.price_modifier = this.three_quarter_price_modifier; boolAdd = true; }
                break;
            case 'full':
                if (isNaN(this.full_price_modifier)) { if (this.id == LengthSelected) { this.price_modifier = null; LengthSelected = null; } } else { this.price_modifier = this.full_price_modifier; boolAdd = true; }
                break;
            default:
                alert('no system selected');boolAdd=true;
                break;
        }
        if (boolAdd) {
            $('length_container').insert(this.template.evaluate({ id: this.id, title: this.title, checked: (this.id == LengthSelected ? 'checked' : '') }));
            if (this.id % 2 == 0) {
                $('length_container').insert('<br class="clear" />');
            }
        }
    }
});

/*
<shipping>
	<name>continental_us</name>
	<description>Continental US</description>
	<base_price>12.95</base_price>
	<large_package_price>20</large_package_price>
</shipping>
*/
var ShippingMethod = Class.create({
  initialize: function(name, description, email_description, base_price, large_package_price, selected) {
    this.id = ShippingMethodIndex;
	this.template = new Template('<dt><input id="shippingmethod_#{id}" name="shippingmethod" value="#{id}" #{checked} onclick="javascript: ShippingMethodSelected = \'#{id}\';" type="radio" /><label for="length_#{id}">#{description}</label></dt>');
	this.name = name;
	this.description = description;
	this.email_description = email_description;
	this.base_price = parseFloat(base_price);
	this.large_package_price = parseFloat(large_package_price);
	
	if( selected == "true" )
	{
		ShippingMethodSelected = ShippingMethodDefault = this.id;
	}	
	ShippingMethodIndex++;
  },
  addElement: function() {
  	$( 'shippingmethod_list' ).insert( this.template.evaluate( {id: this.id, name: this.name, description: this.description, checked: (this.id == ShippingMethodSelected ? 'checked' : '')} ));
  }
});

/*
<subscription>
	<name>1A</name>	
	<description>One time single order</description>
	<price>484</price>
	<payments>1</payments>
	<units_per_package>1</units_per_package>
	<large_package>no</large_package>
</subscription>
*/
var Price = Class.create({
  initialize: function(name, description, price, payments, packages_per_year, units_per_package, large_package, selected) {
    this.id = PriceIndex;
	this.template = new Template('<option value="#{id}" id="price_#{id}" #{selected}>#{description}</option>');
    this.name = name;
	this.description = description;
	this.price = parseFloat(price);
	this.payments = parseFloat(payments);
	this.packages_per_year = parseFloat(packages_per_year);
	this.units_per_package = parseFloat(units_per_package);
	this.large_package = large_package;
	
	if( selected == "true" )
	{
		PriceSelected = PriceDefault = this.id;
	}
	
	PriceIndex++;
  },
  addElement: function() {
  	$( 'price_optionlist' ).insert( this.template.evaluate( {id: this.id, name: this.name, description: this.description, selected: (this.id == PriceSelected ? 'selected="selected"' : '')} ));
  }
});

var Quote = Class.create({
    getMonthCost: function() {
        var tmpValue = ((Prices[this.prices_id].price * Prices[this.prices_id].units_per_package) + (Systems[SystemSelected].price_modifier * Prices[this.prices_id].units_per_package) + (Lengths[LengthSelected].price_modifier * Prices[this.prices_id].units_per_package) + this.shipping_cost) * (1 + this.taxrate) / Prices[this.prices_id].payments;
        return parseFloat((tmpValue).toFixed(2));
    },
    getSystemCost: function(includeTax) {
        var tmpValue = (Prices[this.prices_id].price + Systems[SystemSelected].price_modifier + Lengths[LengthSelected].price_modifier + this.shipping_cost);
        if (includeTax) {
            tmpValue = tmpValue * (1 + this.taxrate);
        }
        return parseFloat((tmpValue).toFixed(2));
    },
    initialize: function(prices_id) {
        this.upsell_template = new Template('<tr class="#{row_class}"><td>#{packages}</td><td>#{cost_per_system}<!-- per system --></td><td>#{cost_per_month}<!-- per month --></td></tr>');
        this.prices_id = prices_id;
        this.packages_per_year = Prices[this.prices_id].packages_per_year;
        this.taxrate = 0;
        this.cost_per_month = 0.00;
        this.cost_per_system = 0.00;
        this.tax_per_system = 0.00;
        this.unit_discount = "$0.00";
        this.includes_message = "";

        this.shipping_cost = (Prices[this.prices_id].large_package == 'no' ? ShippingMethods[ShippingMethodSelected].base_price : ShippingMethods[ShippingMethodSelected].large_package_price);

        if ($('pa_taxrate').checked) {
            this.taxrate = parseFloat($('pa_taxrate').value);
        }

        if (this.packages_per_year > 1) {
            this.cost_per_month = this.getMonthCost();
            this.cost_per_system = this.getSystemCost(false);
        }
        else {
            this.cost_per_system = this.getSystemCost(false);
        }

        this.tax_per_system = parseFloat((this.cost_per_system * this.taxrate).toFixed(2));

        this.cost_per_system = parseFloat((this.cost_per_system + this.tax_per_system).toFixed(2));

        this.unit_subtotal = parseFloat((Prices[this.prices_id].price + Systems[SystemSelected].price_modifier).toFixed(2));

        if (this.prices_id > 1) {
            this.unit_discount = formatCurrency(this.unit_subtotal - Quotes[1].unit_subtotal);
        }
    },
    addUpsellRow: function() {
        if (UPSELL_COUNT % 2 == 0) {
            var row_class = 'even';
        }
        else {
            var row_class = 'odd';
        }

        $('upsell_body').insert(this.upsell_template.evaluate({ packages: this.packages_per_year + ((this.prices_id == parseInt(PriceSelected) + 1) ? " hair systems per year<!-- ... -->" : "<!-- hair systems --> per year<!-- ... -->"), cost_per_system: formatCurrency(this.cost_per_system), cost_per_month: formatCurrency(this.cost_per_month), row_class: row_class }));
    }

});

function initialize()
{
	loadXmlObjects();
	
	Steps.each(function(element){ if(typeof(element) != 'undefined'){ element.addElement(); } });

	Systems.each(function(element){ if(typeof(element) != 'undefined'){ element.addElement(); } });
	
	ShippingMethods.each(function(element){ if(typeof(element) != 'undefined'){ element.addElement(); } });	
	
	Prices.each(function(element){ if(typeof(element) != 'undefined'){ element.addElement(); } });

	if (SystemSelected != null) {
	    handleSystem(SystemSelected);
	}
	
	if(PriceSelected == null) { $('price_optionlist').selectedIndex = 0; } else { $A($('price_optionlist').options).each( function(element){ (element.value == PriceSelected ? element.selected=true : ''); } ); }

	Event.observe('btnCalculate', 'click', processQuote);
	/*Event.observe('btnReset', 'click', resetCalculator);*/
}


function handleSystem(system_id)
{	
	SystemSelected = system_id;
	$('length_container').update('');	
	Lengths.each( function(element){ if(typeof(element) != 'undefined'){ element.addElement(); } });	
}

function resetCalculator() {
    $('aspnetForm').reset();    
    SystemSelected=SystemDefault, LengthSelected=LengthDefault, PriceSelected=PriceDefault, ShippingMethodSelected=ShippingMethodDefault;
    $('btnCalculate').value = 'Calculate';
    $('hit_calculate').update("Hit the 'Calculate' button above for totals...");
    $('length_container').update('');
    
    if (SystemSelected != null) {
        handleSystem(SystemSelected);
    }
    
    $$('#step_5 .amount').invoke('update', '$0.00');
    $$('#container .reset', '#response_flasher #flash_error').invoke('hide');
}

function beforeCalculations()
{
	UPSELL_COUNT = 0;
	$$('.flash_message').invoke('remove');
	$$('#step_5 .toggle', '#step_5 #breakdown', '#step_5 #upsell', '#step_5 .upsell_link').invoke('hide');
	
	$$('#step_5 .dynamic','div.error').invoke('update', '');	
	$('cost_per_month','cost_per_system').invoke('update',formatCurrency(0));
}

function afterCalculations()
{
    if ($('upsell_body').empty()) {
        $$('#step_5 .toggle', '#step_5 .breakdown_link').invoke('show');
    }
    else {
        $$('#step_5 .toggle', '#step_5 .breakdown_link', '#step_5 .upsell_link').invoke('show');
    }
    
    $('btnCalculate').value = 'Re-calculate';
    $('hit_calculate').update("Hit the 'Re-calculate' button above for totals...");

    $('breakdown_system').update( Systems[ SystemSelected ].email_description );
    $('breakdown_system_cost').update("<!--(-->" + formatCurrency(Quotes[PriceSelected].unit_subtotal) + "<!--)-->");
    
    $('breakdown_length').update( Lengths[ LengthSelected ].title + " of hair length" );
    $('breakdown_length_cost').update("<!--(-->" + formatCurrency(Lengths[LengthSelected].price_modifier) + "<!--)-->");
    
    $('breakdown_shipping').update( 'Shipping ' + ShippingMethods[ ShippingMethodSelected ].email_description );
    $('breakdown_shipping_cost').update("<!--(-->" + formatCurrency(Quotes[PriceSelected].shipping_cost) + "<!--)-->");
    
    if( Prices[PriceSelected].packages_per_year > 1 )
    {
        $('breakdown_discount').update( 'Standing Order ' + Prices[ PriceSelected ].name + ' discount' );
        $('breakdown_discount_cost').update("<!--(-->" + Quotes[PriceSelected].unit_discount + "<!--)-->");
    }
    
    if( Quotes[PriceSelected].tax_per_system > 0 )
    {
        $('breakdown_row_tax').show();
        $('breakdown_tax').update( '6% sales tax for Pennsylvania' );
        $('breakdown_tax_cost').update("<!--(-->" + formatCurrency(Quotes[PriceSelected].tax_per_system) + "<!--)-->");
        $('breakdown_row_tax').addClassName('odd');
    }
    else
    {
        $('breakdown_row_tax').hide();
        $('breakdown_row_tax').removeClassName('odd');
    }
}

function validation()
{
	var isValid = true;
	if(PriceSelected == null || !$('price_'+PriceSelected))
	{
		isValid = false;
		$('price_message').update('Oops! Please choose an order type.').show();
	}
	
	if(SystemSelected == null || !$('system_'+SystemSelected))
	{
		isValid = false;
		$('system_message').update('Oops! System is required.').show();
	}
	
	if(LengthSelected == null || !$('length_'+SystemSelected))
	{
		isValid = false;
		if(SystemSelected == null || !$('system_'+SystemSelected))
		{
		    $('length_message').update('').show();			
		}
		else
		{
		    $('length_message').update('Oops! Length is required.').show();
		}
	}
	
	if(ShippingMethodSelected == null || !$('shippingmethod_'+ShippingMethodSelected))
	{
		isValid = false;
		$('shippingmethod_message').update('Oops! Shipping method is required.').show();
	}
	return isValid;
}

function processQuote()
{
	beforeCalculations();

	if(validation())
	{ //our form fields are filled out properly
		Prices.each(function(element){ if(typeof(element) != 'undefined'){ Quotes[element.id] = new Quote(element.id); } });

		Quotes.each(function(element) {
		    if (typeof (element) != 'undefined') {
		        if (element.prices_id == PriceSelected) {
		            if (element.packages_per_year == 1) {
		                /*$('cost_order_label').update('Single order of 1 hair system...');*/
		                $('upsell_note').update('You chose 1 hair system, but for only a few more dollars you can get many more units...');

		                element.includes_message = 'Single order of 1 hair system, a ' + Systems[SystemSelected].email_description.toLowerCase() +' with ' + Lengths[LengthSelected].title + ' of hair length, delivered ' + ShippingMethods[ShippingMethodSelected].email_description;
		            }
		            else {
		                /*$('cost_order_label').update('Standing Order ' + element.packages_per_year + ' hair systems per year...');*/
		                $('upsell_note').update('You chose ' + element.packages_per_year + ' hair systems per year, but for only a few more dollars you can get many more units...');

		                element.includes_message = 'Standing Order ' + element.packages_per_year + ' hair systems per year, a ' + Systems[SystemSelected].email_description.toLowerCase() + ' with ' + Lengths[LengthSelected].title + ' of hair length, delivered ' + ShippingMethods[ShippingMethodSelected].email_description;
		            }

		            $('cost_per_system').update(formatCurrency(element.cost_per_system));
		            $('cost_per_month').update(formatCurrency(element.cost_per_month));

		            if (element.cost_per_month > 0) {
		                $('monthly_upsell_message').update('How can I save even more?');
		            }
		            else {
		                $('monthly_upsell_message').update('How can I pay monthly and save on every hair system?');
		            }
		        }
		        else if (element.prices_id > PriceSelected) {
		            UPSELL_COUNT++;
		            element.addUpsellRow();
		        }
		    }
		});
	    afterCalculations();
	}
}

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));
    }
    
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function emailQuote()
{
    $$('.flash_message').invoke('remove');
    var strParams = "";

    $$('.serialize').each(function(element) { strParams += "&" + element.id + "=" + encodeURIComponent(element.innerHTML); });
    strParams += "&email_address=" + encodeURIComponent( $('email_address').value );
    
    strParams += ( $('email_offers').checked ? "&email_offers=1" : "" );
    strParams += ( $('pa_taxrate').checked ? "&pa_taxrate=1" : "" );
    
    strParams += "&includes_message=" + encodeURIComponent( Quotes[PriceSelected].includes_message );
    strParams += "&right_col_image=" + loadRandomHeader();
    $('loading').update('<img src="../../../gui/images/calculator/progress.gif" />');

    $('btnEmail').hide();
   
    new Ajax.Updater('response_container', 'http://www.hairdirect.com/hair/replacement/costs/calcHandler.ashx', {
        method: 'post',
        parameters: strParams,
        onComplete: function(transport) {
            $('btnEmail').show();
            $('loading').update('');
            var response = $('postResponse').value;
            var message = $('postMessage').value;
            var flashStyle;

            if (response.match(/OK/)) {
                flashStyle = "flash_ok";
                
                resetCalculator();
            }
            else {
                flashStyle = "flash_error";
            }
            $('response_flasher').insert({ top: new Element('div', { 'class': 'flash_message', 'id': flashStyle }).update(message) });
            $$('.flash_message').each(function(element) { Effect.Pulsate(element, { pulses: 2, duration: 1.5 }) });

        }
    });
}
Event.observe(window, 'load', initialize, false );

function loadRandomHeader() {
    images = new Array(3);

    images[0] = "right_header_1.jpg";
    images[1] = "right_header_2.jpg";
    images[2] = "right_header_3.jpg";
    index = Math.floor(Math.random() * images.length);
    
    return images[ index ];
}
function RF(el, radioGroup) 
{
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
    var checked = null;
    for(var x=0; x < document.forms[el][radioGroup].length; x++)
    {
        if(document.forms[el][radioGroup][x].checked)
        {
            checked = document.forms[el][radioGroup][x].value;
        }
    }
    return checked;
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

//var value = $RF('radio_btn_id');
//var value = $RF('form_id', 'radio_grp_name');

/*
"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$"
Steps[StepIndex] = new Step('1', '1', 'Size of hair system', '');
Steps[StepIndex] = new Step('2', '2', 'Extra hair length', 'a.	An extra fee applies if your hair style requires more than 6� of length.');
Steps[StepIndex] = new Step('3', '3', 'Type of order', 'You can order one system at a time or, if you need more than one unit per year, pay monthly and save big with a standing order.');
Steps[StepIndex] = new Step('4', '4', 'Shipping', 'Where will your hair be shipped?');
Steps[StepIndex] = new Step('5', '$', 'Totals', 'Hit the `Calculate` button to generate quote.');


Systems[SystemIndex] = new System( 'partial', 'Partial Piece', 'Top of head, anything smaller than 6x9', '0', false );
Systems[SystemIndex] = new System( 'three_quarter', '3/4 Cap', 'Top and sides of head, anything between 7x9 and 9x11', '60', false );
Systems[SystemIndex] = new System( 'full', 'Full Cap', 'Top of head, anything larger than 9x11', '110', false );


Lengths[LengthIndex] = new Length('8 Inches', '30', '30', '35', true );
Lengths[LengthIndex] = new Length('10 Inches', '55', '55', '65', false );
Lengths[LengthIndex] = new Length('12 Inches', '85', '85', '95', false );
Lengths[LengthIndex] = new Length('14 Inches', '85', '85', '', false );


ShippingMethods[ShippingMethodIndex] = new ShippingMethod('continental_us', 'Continental US', '12.95', '20', true );
ShippingMethods[ShippingMethodIndex] = new ShippingMethod('akhipr', 'Alaska, Hawaii, and Puerto Rico', '21.95', '21.95', false );
ShippingMethods[ShippingMethodIndex] = new ShippingMethod('international', 'International (Outside US)', '36', '36', false );


Prices[PriceIndex] = new Price ( '1A', 'One time single order', '484', '1', '1', '1', 'no', false );
Prices[PriceIndex] = new Price ( '2A', '2 standing orders per year', '449', '6', '2', '1', 'no', false );
*/