var min_width=0;
var max_width=0;
var min_drop=0;
var max_drop=0;
var price=0;
var shape_price=0;
var discount=0;

var discountrm=0;
var price_rm=0;
var price_mm=0;

function sortArrayPrice(a,b){
	return(a-b);
}

// MM
var arr = new Array();
arr = eval('Array('+blackoutmm_arr[4][3]+')');
var sorter = new Array();
sorter = arr.sort(sortArrayPrice);
/*
// RM
var arrRM = new Array();
if(typeof(blackout_arr) != "undefined" && blackout_arr.length > 0) {
	arrRM = eval('Array('+blackout_arr[3]+')');
}
var sorterRM = new Array();
sorterRM = arrRM.sort(sortArrayPrice);
*/
function getMinimumPrice(){
	var minpriceMM = minpriceRM = 9999;
	
	// MM
	minP = sorter;
	minpriceMM = (minP[0].toFixed(2) * (1-discount_)).toFixed(2);
	
	mp = minpriceMM;
	if(typeof(sale) != 'undefined' && sale.sale > 0)
		mp = formatDecimal(mp - (mp * sale.sale /100), true,2);
	document.getElementById('minprice').innerHTML = mp;
	
}

function CheckReferrer() {
	var ref = document.referrer;

	params = getParams();
	var nd = 0; // nextday parameter
	if(params["nd"] == 1)
		nd = 1;

	if(ref != "http://www.blindsuk.net/roller-next-day.html" && ref != "http://www.blindsuk.net/roller-next-day-page-1.html" && nd == 0) {
		document.form_calcblackoutmm.nextday.selectedIndex = 0; // select standard delivery
	}
	else {
		document.form_calcblackoutmm.nextday.selectedIndex = 1; // select default NEXTDAY
	}
}

function getParams()
{
	var idx = document.URL.indexOf('?');
	var params = new Array();
	if (idx != -1)
	{
		var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
		for (var i=0; i<pairs.length; i++)
		{
			nameVal = pairs[i].split('=');
			params[nameVal[0]] = nameVal[1];
		}
	}
	return params;
}


function SetOtherParams()
{
    params = getParams();
    if (params["controls"] && params["recess"])
    {
        document.form_calcblackoutmm.controls.value = params["controls"];
        document.form_calcblackoutmm.recess.value = params["recess"];
    }
}

function SetParams()
{
	ArenaScallops.get_scallops(assigned_scallop.scallops_tree);
	
	min_width=parseInt(blackoutmm_arr[0]);
	max_width=parseInt(blackoutmm_arr[1]);
	min_drop=parseInt(blackoutmm_arr[2]);
	max_drop=parseInt(blackoutmm_arr[3]);
	
	discount=parseFloat(blackoutmm_arr[4]);
	
	params = getParams();
	
	width = params["width"];
	drop = params["drop"];

	outside = params["outside"];

	// default recess OUTSIDE when coming from QQ
	if((outside!="")&&(typeof(outside) != "undefined")) {
		document.form_calcblackoutmm.recess.value = "Outside";
		var recess=document.form_calcblackoutmm.recess.value;
	}

	if((width!="")&&(typeof(width) != "undefined"))
		document.form_calcblackoutmm.custom_width.value=unescape(width);
	if((drop!="")&&(typeof(drop) != "undefined"))
		document.form_calcblackoutmm.custom_drop.value=unescape(drop);
	if((document.form_calcblackoutmm.custom_width.value!="")&&(document.form_calcblackoutmm.custom_drop.value!=""))
		GetCustomPrice();
}

function formatDecimal(argvalue, addzero, decimaln) {
  var numOfDecimal = (decimaln == null) ? 2 : decimaln;
  var number = 1;

  number = Math.pow(10, numOfDecimal);

  argvalue = Math.round(parseFloat(argvalue) * number) / number;
  
  argvalue = "" + argvalue;

  if (argvalue.indexOf(".") == 0)
    argvalue = "0" + argvalue;

  if (addzero == true) {
    if (argvalue.indexOf(".") == -1)
      argvalue = argvalue + ".";

    while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal))
      argvalue = argvalue + "0";
  }

  return argvalue;
}

function ChangePrice(custom_ctrl, form_calc)
{
	custom_ctrl.value="";
	form_calc.price.value="";
	form_calc.saveprice.value="";
}

function GetPrice(prices_arr, width, drop, comision)
{
	var min_dif_width=-1, min_dif_drop=-1;
	var sel_width=-1, sel_drop=-1;
	var price=0;
	for(i=0;i<prices_arr[0].length;i++)
	{
		var cur_dif_width=prices_arr[1][i]-width;
		var cur_dif_drop=prices_arr[2][i]-drop;
		//alert("dif curenta: "+cur_dif_width+"   width: "+sizes_arr[1][i]+" custom width:"+custom_width);
		if(((min_dif_width==-1)||(cur_dif_width<min_dif_width))&&(cur_dif_width>=0))
		{
			min_dif_width=cur_dif_width;
			sel_width=prices_arr[1][i];
			sel_drop=-1;
			min_dif_drop=-1;
		}
		
		if(prices_arr[1][i]==sel_width)
			if(((min_dif_drop==-1)||(cur_dif_drop<min_dif_drop))&&(cur_dif_drop>=0)&&(min_dif_width!=-1))
			{
				min_dif_drop=cur_dif_drop;
				sel_drop=prices_arr[2][i];
				price = (!comision)? prices_arr[3][i] : prices_arr[4][i];
			}
	}
	return price;
}


function GetRMPrice(custom_width, custom_drop)
{
	document.form_calcblackoutmm.blackout.value=0;
	var priceRM = 0;

	//document.form_calcblackout.price.value = '';
	//document.form_calcblackout.saveprice.value = '';
	for(i=0; i<blackout_arr[1].length; i++)
	{
		if(custom_width == blackout_arr[1][i] && custom_drop == blackout_arr[2][i])
		{
			document.form_calcblackoutmm.blackout.value=i+1;
			priceRM = blackout_arr[3][i];
			
		}
	}
	
	return priceRM;
}

function GetMaxWidth(prices_arr, drop)
{
	var max_width=0;
	var min_dif_drop=-1;
	var sel_drop=-1;
	for(i=0;i<prices_arr[0].length;i++)
	{
		var cur_dif_drop=prices_arr[2][i]-drop;
		if(((min_dif_drop==-1)||(cur_dif_drop<min_dif_drop))&&(cur_dif_drop>=0))
		{
			min_dif_drop=cur_dif_drop;
			sel_drop=prices_arr[2][i];
			max_width=0;
		}
		
		if((prices_arr[2][i]==sel_drop)&&(max_width<prices_arr[1][i]))
			max_width=prices_arr[1][i];
	}
	return max_width;
}

function GetCustomPrice()
{
	var scallop_price = parseFloat(ArenaScallops.get_price($('scallops').value, document.form_calcblackoutmm.custom_width.value));
	var price = 0;
	var custom_width=parseInt(document.form_calcblackoutmm.custom_width.value);
	var custom_drop=parseInt(document.form_calcblackoutmm.custom_drop.value);
	if((min_width>custom_width)||(max_width<custom_width)||(isNaN(custom_width)))
	{
		alert("Please enter width between "+min_width+"mm (min) and "+max_width+"mm (max)");
		return false;
	}
	if((min_drop>custom_drop)||(max_drop<custom_drop)||(isNaN(custom_drop)))
	{
		alert("Please enter drop between "+min_drop+"mm (min) and "+max_drop+"mm (max)");
		return false;
	}
	
	// check width & drop for maximum (if joint possible)
	/* -------------------------------------------------- */
	if(join_condition != '0') { 
		if(custom_drop > join_max_drop && custom_width > join_max_width) { // join limits overrun
			if(join_condition == '2') { // check on drop
				alert("Maximum width for the selected drop is "+join_max_width+" mm");
				document.form_calcblackoutmm.custom_width.value = '';
				document.form_calcblackoutmm.custom_width.focus();
				return false;
			}
			if(join_condition == '1') { // check on width
				alert("Maximum drop for the selected width is "+join_max_drop+" mm");
				document.form_calcblackoutmm.custom_drop.value = '';
				document.form_calcblackoutmm.custom_drop.focus();
				return false;			
			}
		} // end if join limits overrun
	} // end if join condition
	/* -------------------------------------------------- */

	var recess=document.form_calcblackoutmm.recess.value;
	document.form_calcblackoutmm.blackout.value=0;
	
	if(recess=="Inside")
		custom_width -= 3;

	/* REMOVED
	if(typeof(blackout_arr) != "undefined" && document.form_calcblackoutmm.nextday.value == 0) { // maybe RM price, but not on nextday!
		discountrm = blackout_arr[0];
		discount=discountrm;
		//alert("Width : " + custom_width + "\nDrop: " + custom_drop);
		price=GetRMPrice(custom_width, custom_drop);
		price_rm=price;
		//alert("Price RM: " + price);
	}
	else
	*/
		price_rm = 0;
	
	if(recess=="Inside")
		custom_width += 3;
		
	price_mm = GetPrice(blackoutmm_arr[4], custom_width, custom_drop);
	
	if(!price || price == 0)
	{
		//alert('NU AM PRET DE RM!');
		//discount=parseFloat(blackoutmm_arr[4]); // MM discount
		discount = discount_;
		price = price_mm;
		if(price == 0) {
			var strMaxWidth=GetMaxWidth(blackoutmm_arr[4], custom_drop);
			alert("Maximum width for the selected drop is "+strMaxWidth+" mm");
			return;
		}
	}

	
	// nextday price
	//var delivery = document.form_calcblackoutmm.nextday;
	/*
	if ((custom_width > 1900 && custom_drop >= 1700) || (custom_drop > 2700)){ // no nextday dimensions (JOINT!)
		if(delivery.selectedIndex == 0){
			alert("Next day service is not available for these sizes!");
		}
		delivery.selectedIndex = 1; // select standard
		document.form_calcblackoutmm.nextday2.selectedIndex = 1; // select standard		
	}
	*/
	var delivery_price = 0;
	/*
	if (delivery.value != 0 && discount != 1)
		delivery_price = 5 / (1 - discount);
	*/
	// controls price
	/* ******************************************************* */
	
	/* TEMPORARY: NO NEXTDAY FOR SPRING CONTROLS */
	// if not normal controls (plastic left, plastic right, metal left, metal right)
	/*
	if(sel_controls != 0 && sel_controls != 1 && sel_controls != 2 && sel_controls != 3 && delivery.selectedIndex == 1) {
		alert("Next day service is not available on this option!");
		delivery_price = 0;
		delivery.selectedIndex = 0; // select standard
		//document.form_calcblackoutmm.nextday2.selectedIndex = 1; // select standard
	}
	*/
	/* [END] NO NEXTDAY FOR SPRING CONTROLS */
	
	if($('scallops') && $('scallops').options.selectedIndex > -1 ){
		selected_scallop = $('scallops')[$('scallops').options.selectedIndex].innerHTML.strip();
	}
  else selected_scallop = 'Shape 1';
	
	var controls_price = 0;
	var controls = document.form_calcblackoutmm.controls.value;
	//controls_price = controls_price / (1 - discount);

	// CHECK CONTROLS (spring controls only for shapes 1-4 & 9, max width 2m) */
	checkControls(controls, selected_scallop, custom_width);

	// [END] CONTROLS
	/* ******************************************************* */
	
	// CHECK BRAIDS (insert in hidden field value from select field)
	//document.form_calcblackoutmm.braid.value = document.form_calcblackoutmm.braids.value;
	
	/***** SCALLOPS  ****/
	/*sel = new ComboSelect('braids');
		sel.select_braids(22);*/
	//custom_width, custom_drop
	
	/*
	if(document.form_calcblackoutmm.recess.value == 'Outside' || document.form_calcblackoutmm.recess.value == 'Inside' ){ 
		if(custom_width > 2963 && (selected_scallop == 'classic' || selected_scallop == 'provence') ){
			$('scallops')[0].selected = true;
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2963 mm.');
		}
		if(custom_width > 2980 && selected_scallop == 'colonial'){
			$('scallops')[0].selected = true;			
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2980 mm.');
		}
		if(custom_width > 2927 && selected_scallop == 'coronet'){
			$('scallops')[0].selected = true;
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2927 mm.');
		}
	}
	
	if(document.form_calcblackoutmm.recess.value == 'Cloth'){ 
		if(custom_width > 2928 && (selected_scallop == 'classic' || selected_scallop == 'provence')){
			$('scallops')[0].selected = true;
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2928 mm.');
		}
		if(custom_width > 2945 && selected_scallop == 'colonial'){
			$('scallops')[0].selected = true;
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2945 mm.');
		}
		if(custom_width > 2892 && selected_scallop == 'coronet'){
			$('scallops')[0].selected = true;
			new ScallopsOptions();
			return alert('Maximum width for the selected scallop is 2892 mm.');
		}
	}
	
	if(custom_width < 660 && selected_scallop == 'coronet'  ){
		$('scallops')[0].selected = true;
		new ScallopsOptions();
		return alert('Minimum width for the selected scallop is 660 mm.');
	}
	*/
	
	
	comision = GetPrice(blackoutmm_arr[4], custom_width, custom_drop, true); 
	braids_price = 0;	
	/*
	if(document.form_calcblackoutmm.cafe_rods && document.form_calcblackoutmm.cafe_rods.type != 'hidden' )
		caferods_price = parseFloat(new GetScallopsPrice(document.form_calcblackoutmm.cafe_rods.value, custom_width, custom_drop).s_price)  * comision * minus * (1+com);
	else
	*/
	caferods_price = 0;
	//console.log('Braids: '+braids_price +"\r\n"+'Bottom bar: '+bottombar_price+'\r\nCafe rods: '+caferods_price);
	scallop_price = scallop_price * comision * minus * (1+com);
	
	var total_price = 
					price + 
					delivery_price + 
					controls_price + 
					scallop_price + 
					braids_price+
					caferods_price; 

	var save_price = total_price * discount;
	
	document.form_calcblackoutmm.price.value = formatDecimal(total_price-save_price, true, 2);
	document.form_calcblackoutmm.saveprice.value = formatDecimal(save_price, true, 2);
	
	document.form_calcblackoutmm.addtobasket.disabled=false;
	
	RRP.get();
}

function VerifyBlackoutMMForm(form)
{
	if(form.price.value<=0)
	{
		alert('Please insert width and drop first and click the button "Calculate Price"');
		return false;
	}
	return true; 
}

function SelectProdType(prodtype)
{
		window.location = prodtype;
}

function onChangeCloth(){
	if (document.form_calcblackoutmm.recess.value == "Cloth"){
		alert("Please note that the end brackets will add to the cloth size 35mm - 50mm and may not fit inside recess.");
	}
}

function SelNextday(source_value, destination) {
	if(source_value == 0) // no nextday
		destination.selectedIndex = 1; // select standard
	else
		destination.selectedIndex = 0; // select nextday
}

function checkControls(control, scallop, width) {
	if(control != 'Right' && control != 'Left' && scallop != "Shape 1" && scallop != "Shape 2" && scallop != "Shape 4" && scallop != "Shape 9") {
		alert("Sorry, spring controls are available for Shapes 1-4 and 9 only!");
		document.form_calcblackoutmm.controls.selectedIndex = 0;
	}
	else if(control != 'Right' && control != 'Left' && width > 2000) {
		alert("Maximum width for spring controls is 2000mm.");
		document.form_calcblackoutmm.controls.selectedIndex = 0;
	}
} 

var ArenaScallops = {
	init:function(){
			ArenaScallops.get_braids($('scallops').value);
			ArenaScallops.get_caferods($('scallops').value);
	},
	get_scallops:function(product_id)
	{
		new Ajax.Request('http://www.blindsuk.net/inc/roller_scallops.php', {
		asynchronous:false,
		parameters:{'product_id':product_id, 'action': 'get_scallops'},
		onComplete: function(transport){
			result = transport.responseText.evalJSON();
			var i = 0;
			result.each(function(pair){
					$('scallops')[i++] = new Option(pair.label, pair.id);
					if(pair.selected == 1){
						$('scallops').options[i-1].selected = true;
					}
			});
      
			ArenaScallops.init();
			$('scallops').observe('change', function(){
				ArenaScallops.get_braids($('scallops').value);
				ArenaScallops.get_caferods($('scallops').value);
			});
		}
		});
	},
	get_caferods:function(scallop){
		new Ajax.Request('http://www.blindsuk.net/inc/roller_scallops.php', {
		parameters:{'scallop':scallop, 'action': 'get_cafe_rods'},
		onComplete: function(transport){
			result = transport.responseText.evalJSON();
			$('cafe_rods').length = 0;
			var i = 0;
			if(result.length == 0){
				$('cafe_rods')[i++] = new Option("No", 0);
			}
			result.each(function(pair){
					$('cafe_rods')[i++] = new Option(pair.label, pair.id);
					if(pair.selected == 1){ 
						$('cafe_rods').options[i-1].selected = true;
					}
			});
		}
		});
	},
	get_braids:function(scallop){
		new Ajax.Request('http://www.blindsuk.net/inc/roller_scallops.php', {
		parameters:{'scallop':scallop, 'action':'get_braids'},
		onComplete: function(transport){
//			result = transport.responseText.evalJSON();
//			$('braids').length = 1;
//			var i = 1;
//			result.each(function(pair){
//					$('braids')[i++] = new Option(pair.label, pair.id);
//					if(pair.selected == 1){
//						$('braids').options[i-1].selected = true;
//					}
//			});
      var braids = transport.responseText.evalJSON();
      new Combo('braids', {handler: 'braids_event_handler', populate_data:braids, input:'braid'});
		}
		});
	},
	get_price:function(id, width){
		new Ajax.Request('http://www.blindsuk.net/inc/roller_scallops.php', {
		asynchronous:false,
		method:'post',
		parameters:{'id':id, 'action':'get_price', 'width':width},
		onComplete: function(transport){
			result = transport.responseText;
			//alert( result);			
		}
		});
		return result;
	}
}
/*
Event.domReady.add(function(){
	ArenaScallops.get_scallops(assigned_scallop.scallops_tree);
});
*/

function removeSelectOptions(selectObj) {
  if (selectObj != null && selectObj.options != null) {
    numkids = selectObj.options.length - 1;
    for (var i = numkids; i >= 0; i--) {selectObj.remove(i);}
  }
  return true;
}

function addSelectOption(selectObj, text, value, isSelected) {
  if (selectObj != null && selectObj.options != null) {
    selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);
  }
  return true;
}

function check_shape () {
  if ($('scallops') && $('scallops').options.selectedIndex > -1) {
    sc_name = $('scallops')[$('scallops').options.selectedIndex].innerHTML.strip();

      if (sc_name == 'Shape 1' || sc_name == 'Shape 2' || sc_name == 'Shape 3' || sc_name == 'Shape 4' || sc_name == 'Shape 9') {
        //do nothing
      }
      else {
        if ( $('controls').value == 'Left' || $('controls').value == 'Right' ) {
          //do nothing
        }
        else {
        return false;
      }
    }
  }
  return true;
}

function check_controls_colors() {
  if ( check_shape() == false ) return false;
  if ( $('controls').value == 'Ring Pull' ) {
    $('controls_colors').setStyle({display: 'block'});
    $('controls_colors_text').setStyle({display: 'block'});
    removeSelectOptions($('controls_colors'));
    addSelectOption($('controls_colors'), 'White', 'White', true);
    addSelectOption($('controls_colors'), 'Cream', 'Cream', false);
    addSelectOption($('controls_colors'), 'Beige', 'Beige', false);
  }
  else if ( $('controls').value == 'Wooden Dolly Pull' ) {
    $('controls_colors').setStyle({display: 'block'});
    $('controls_colors_text').setStyle({display: 'block'});
    removeSelectOptions($('controls_colors'));
    addSelectOption($('controls_colors'), 'White', 'White', true);
    addSelectOption($('controls_colors'), 'Ivory', 'Ivory', false);
    addSelectOption($('controls_colors'), 'Beige', 'Beige', false);
  }
  else {
    $('controls_colors').setStyle({display: 'none'});
    $('controls_colors_text').setStyle({display: 'none'});
    removeSelectOptions($('controls_colors'));
    addSelectOption($('controls_colors'), 'none', '0', true);
  }
  return true;
}


var RollerMMOptions = Class.create({
	initialize:function(var_name)
  {
    this.main_select_obj = $(var_name);
    this.select_obj = $(var_name+'_colors');
    this.select_text_obj = $(var_name+'_colors_text');
    this.shown_selected_extra = false;
		_self = this;
	},
  check_selected_scallops:function()
  {
    if ($('scallops') && $('scallops').options.selectedIndex > -1) {
      sc_name = $('scallops')[$('scallops').options.selectedIndex].innerHTML.strip();
      if (sc_name == 'Shape 1' || sc_name == 'Shape 2' || sc_name == 'Shape 3' || sc_name == 'Shape 4' || sc_name == 'Shape 9') {
        //do nothing
      }
      else {
        if ( this.main_select_obj.value == 'Left' || this.main_select_obj.value == 'Right' ) {
          //do nothing
        }
        else {
          alert('Only Chain on Left and Chain on Right Controls are available with this scallop!');
          this.main_select_obj.options[0].selected = true;
          if (this.shown_selected_extra == true) this.remove_controls_colors(this.select_obj);
        }
      }
    }
    return true;
  },
  check_selected_color:function()
  {
    if ($('scallops') && $('scallops').options.selectedIndex > -1) {
      sc_name = $('scallops')[$('scallops').options.selectedIndex].innerHTML.strip();
      if (sc_name == 'Shape 1' || sc_name == 'Shape 2' || sc_name == 'Shape 3' || sc_name == 'Shape 4' || sc_name == 'Shape 9') {
        //do nothing
      }
      else {
        if ( this.main_select_obj.value == 'Left' || this.main_select_obj.value == 'Right' ) {
          //do nothing
        }
        else {
          alert('Only Chain on Left and Chain on Right Controls are available with this scallop!');
          this.main_select_obj.options[0].selected = true;
          if (this.shown_selected_extra == true) this.remove_controls_colors(this.select_obj);
        }
      }
    }
    return true;
  },
  update_select_options:function()
  {
    switch (this.main_select_obj.value) {
      case 'Ring Pull':
        this.set_options_rings();
      break;
      case 'Wooden Dolly Pull':
        this.set_options_dolly();
      break;
      default:
        this.remove_controls_colors();
      break;
    }
    return this;
  },
  remove_controls_colors:function()
  {
    this.select_text_obj.setStyle({display: 'none'});
    this.shown_selected_extra = false;
    this.remove_select_options(this.select_obj)
      .add_select_option(this.select_obj, 'none', '0', true);
    return this;
  },
  set_options_rings:function()
  {
    this.select_text_obj.setStyle({display: 'block'});
    this.shown_selected_extra = true;
    this.remove_select_options(this.select_obj)
      .add_select_option(this.select_obj, 'White', 'White', true)
      .add_select_option(this.select_obj, 'Cream', 'Cream', false)
      .add_select_option(this.select_obj, 'Beige', 'Beige', false);
    return this;
  },
  set_options_dolly:function()
  {
    this.select_text_obj.setStyle({display: 'block'});
    this.shown_selected_extra = true;
    this.remove_select_options(this.select_obj)
      .add_select_option(this.select_obj, 'White', 'White', true)
      .add_select_option(this.select_obj, 'Ivory', 'Ivory', false)
      .add_select_option(this.select_obj, 'Beige', 'Beige', false);
    return this;
  },
  remove_select_options:function(int_select_obj)
  {
    if (int_select_obj != null && int_select_obj.options != null) {
      numkids = int_select_obj.options.length - 1;
      for (var i = numkids; i >= 0; i--) {int_select_obj.remove(i);}
    }
    return this;
  },
  add_select_option:function(int_select_obj, option_name, option_value, isSelected)
  {
    if (int_select_obj != null && int_select_obj.options != null) {
      int_select_obj.options[int_select_obj.options.length] = new Option(option_name, option_value, false, isSelected);
    }
    return this;
  }
})


var Combo = Class.create({
	//Constructorul
	initialize:function(list, options)
	{

		var _self = this;
		this.list = list;
		if(options)
			_self.set_options(options);

		this.populate();
		this.list_collection = this.get_option_list();
		$(this.list).stopObserving('click'); //Opreste eventul de click daca are
		$(this.list).observe('click', this.drop_down.bindAsEventListener(null,_self)); // Aduaga event de click
	},
	get_list:function()
	{

	},
	// caller
	__call: function(func){
		if(!/\W/.test(func.toString())) {
			var func = eval("this."+func.toString());
			if(typeof(func) === "function"){
				return func;
			}else{
				return false;
			}
		}
	},
	//seteaza atributele obiectului
	set_options:function(options)
	{
		var opt = $H(options).collect(function(el){
			return $A(el);
		});
		for(var i = 0; i< opt.length; i++){
			this[opt[i][0]] = opt[i][1];
		}
	},
	populate:function()
	{
		_self = this;
		this.reset_list();
		var html = DOMBuilder.apply();

		if(this.populate_data == null){
			this.reset_list();
			$(_self.input).value = 0;
			$$('#'+_self.list+' span')[0].innerHTML = 'No Braids';
			$('bottombar').value = 0;
			ScallopsTools.bottom_bar_braids_panel('show_braids');
			var price = new ScallopPrice();
			price.braids_increment();
			return;
		}

		this.populate_data.each( function(s, index){
      if (s.option_type == 'braids' && index == 0) {
        LI = html.LI({style:"background-image:url(../rollermm/images/ar-no-braids-sel.jpg);"},
          html.A({rel:'0', title:'No Braids'},"No Braids")
        );
        Element.writeAttribute(LI, {'value':0}); //Fix stupid for ie6
        $$('#'+_self.list+' ul')[0].appendChild(LI);
      }

      LI = html.LI({ /*"value":parseInt(s.id),*/ style:"background-image:url(../rollermm/images/"+s.image+");"},
        html.A({rel:s.id, title:s.option_name},"")
      );
      Element.writeAttribute(LI, {'value':parseInt(s.id)}); //Fix stupid for ie6
      //Selecteaza prima optiune
      if(s.option_type == 'bottom bar' && index == 0 && s.selected != 1){
        _self.__call(_self.handler)(null, _self, LI);
      }
      // Selecteaza ce e bifat selected in baza de date
      else if(s.selected == 1){
        _self.__call(_self.handler)(null, _self, LI);
      }
			$$('#'+_self.list+' ul')[0].appendChild(LI);
		});
		return true;
	},
	reset_list:function(){
		_self = this;
		list_collection = this.get_option_list();
		list_collection.each(function(element,index){
			//if(element.className != 'first')
			//{
				element.remove();
			//}
		});
	},
	get_option_list:function()
	{
		//var list_collection = (this.list_collection)? this.list_collection : $$('#'+this.list+' li');
		var list_collection =  $$('#'+this.list+' li');
		return list_collection;
	},
	drop_down:function(e,obj)
	{
		var list_collection = obj.get_option_list();
		for(len = 0; len < list_collection.length; len++)
		{
			var default_handler = (obj.handler)? obj.handler : 'event_handler';
			var func_name = obj.__call(default_handler);
			selected_scallop = $('scallops')[$('scallops').options.selectedIndex].innerHTML.strip();
			if(list_collection[len].style.display == 'none' || list_collection[len].style.display == '')
			{
				list_collection[len].observe('click', func_name.bindAsEventListener(null, obj, list_collection[len]));
				if(selected_scallop == 'straight finish with braids' && list_collection[len].className == 'first')
					list_collection[len].makeClipping().setStyle({display:'none'});
				else
					list_collection[len].makeClipping().setStyle({display:'block'});
			}
			else
			{
				list_collection[len].stopObserving('click');
				list_collection[len].undoClipping().setStyle({display:'none'});
			}
		}
	},
	event_handler:function(e, obj, selected){
		var maintext = ('No bottom bar' == selected.innerHTML.strip()) ? 'No bottom bar ' : '';
		$(obj.input).value = 0;
		$$('#'+obj.list+' span')[0].innerHTML = maintext;
		$$('#'+obj.list+' span')[0].setStyle({backgroundImage:selected.style.backgroundImage});
		$(obj.input).value = selected.getElementsByTagName('a')[0].rel;
//		var price = new ScallopPrice();
//		price.bottombar_increment();
	},
	braids_event_handler:function(e, obj, selected)
	{
		if(selected.innerHTML.strip() == 'No Braids'){
			$(obj.input).value = 0;
			$$('#'+obj.list+' span')[0].innerHTML = 'No Braids';
			var price = new ScallopPrice();
			price.braids_increment();
			return;
		}
		try{
			$(obj.input).value = selected.getElementsByTagName('a')[0].rel;
			$$('#'+obj.list+' span')[0].innerHTML = selected.getElementsByTagName('a')[0].title;
			//var price = new ScallopPrice();
			//return price.braids_increment();
		}catch(ex){
			alert('Error!');
		}
	}
});

var ComboSelect = Class.create(Combo, {
	initialize:function(combo)
	{
		this.combo = combo;
		this.list = $(combo).getElementsByTagName('li');

	},
	select_braids:function(selected)
	{
		list = this.list
		for(i=1; i < list.length; i++)
		{
			if(selected && list[i].getElementsByTagName('a')[0].rel == selected)
			{
				$$('#'+this.combo+' span')[0].innerHTML = '';
				$$('#'+this.combo+' span')[0].innerHTML = list[i].getElementsByTagName('a')[0].title;
				$('braid').value = selected;
			}
		}
	},
	select_bb:function()
	{
		list = this.list
		for(i=1; i < list.length; i++)
		{
			if(selected && list[i].getElementsByTagName('a')[0].rel == selected)
			{
				$$('#'+this.combo+' span')[0].innerHTML = '';
				$$('#'+this.combo+' span')[0].setStyle({backgroundImage:list[i].style.backgroundImage});
				$('bottombar').value = selected;
			}
		}
	}

})

Event.domReady.add(function() {
  var RollerMMOptions_obj = new RollerMMOptions('controls');
  if (RollerMMOptions_obj.check_selected_scallops() == true) {
    RollerMMOptions_obj.update_select_options();
  }
  $('controls').observe(
    'change', function()
    {
      if (RollerMMOptions_obj.check_selected_scallops() == true) {
        RollerMMOptions_obj.update_select_options();
      }
    }
  );
  $('scallops').observe(
    'change', function()
    {
      RollerMMOptions_obj.check_selected_color();
    }
  );
});
