/*
�������� � Common.xslt:
<script type="text/javascript">
    disabledByText = "Disabled by: ";
	optionBuilderColorCategory = "Peinture";
</script>
<script src="{$hrefRoot}/static/ob.js" type="text/javascript"></script>

� Car.xslt � <xsl:template match="Header" mode="Option">
����� '<xsl:value-of select="@name"/>'
���, ������ �� ������
*/

//<xsl:choose><xsl:when test="/*/Car/Options/Option[@code=$code]/BuildRules/Rule">
//<xsl:for-each select="/*/Car/Options/Option[@code=$code]/BuildRules/Rule">
//<script>optionBuilder.add("<xsl:value-of select="$code"/>", "<xsl:value-of select="text()"/>", "<xsl:value-of select="@type"/>", "<xsl:value-of select="$clientPrice"/>", "<xsl:value-of select="$category"/>", "<xsl:value-of select="$option/@type"/>");</script>
//</xsl:for-each>
//</xsl:when>
//<xsl:otherwise>
//<script>optionBuilder.add("<xsl:value-of select="$code"/>", null, null, "<xsl:value-of select="$clientPrice"/>", "<xsl:value-of select="$category"/>", "<xsl:value-of select="$option/@type"/>");</script>
//</xsl:otherwise></xsl:choose>

/* � <xsl:template match="Header" mode="Option"> ����� <xsl:element name="input"> ��������: */
//<xsl:attribute name="autocomplete">off</xsl:attribute>


/* Если выбраны более простые фары - мы выбираем адаптивные - они в инклютах..... надо бы деселектит простые фары... ( уних не тникаких условий.... по логике же да */

/*

http://bs106:9200/mmfr/car/7014464/Options
1 / Select 9VK
=> Option builder Select RCM. Correct
2 / Select PNU
=> Option builder does not unselect RCM. Should be because 9VK "exige" RCM
or PNU.

САМО ВСЕ ТУТ ПРОТИВОРЕЧИТ
 */

d= function() {};
//d = console.debug;

var isExt = typeof Ext != "undefined";

if (lang == undefined) var lang = {};
lang["hint"] = {
	//text: "Nous avons une nouvelle fonctionnalité qui peut vous aider à configurer votre voiture et sélectionner des options avec beaucoup plus d'efficacité.",
	text: "Nouveau : le configurateur d'options intelligent",
	text_on: "Le nouveau configurateur activé.",
	on: "Oui, je souhaite essayer le nouveau configurateur.*",
	onWarn: "<br><span style='color:gray;font-size:11px;text-decoration:none;padding-left:5px;'>* Toutes les options sélectionnées seront réinitialisés.</span>",
	off: "Désactiver",
	hide: "Non, merci."
};

// DE
/*
lang = {
    hint: {
		text: "Wir haben eine neue Funktionalität, die Ihnen helfen kann, Ihren Neuwagen zu konfigurieren und effizienter Sonderausstattungen auswählen.",
        text_on: "Der neue Konfigurator ist aktiviert.",
        on: "Ja, I möchte gern Ihren Konfigurator benutzen.*",
		onWarn: "<br><span style='color:gray;font-size:11px;text-decoration:none;padding-left:5px;'>*Alle ausgewählten Sonderausstattungen werden zurückgesetzt.</span>",
        off: "Deaktivieren",
        hide: "Nein, Danke."
    }
};
*/




optionBuilder = function(idPrefix, disabledText) {
    var meR = this;
    
    if(isExt) {
        disabledText = lang("disabledBy");
        selectedText = lang("selectedBy");
        deselectedText = lang("unselectedBy");
        includedText = lang("includedBy");
    }

    this.disabledText = disabledText;
    this.selectedText = selectedText;
    this.deselectedText = deselectedText;
    this.includedText = includedText;

    if(isExt || idPrefix) {
        this.idPrefix = idPrefix;
    } else {
        idPrefix = "";
        this.idPrefix = "";
    }



    if(!isExt) {
        show = function() {
            $(".obHint").show();
            $(".obHint_ON").hide();
        };
        onAuto = function() {
            $.cookie("new_ob", 1);
            optionBuilder.init.createDelegate(optionBuilder)();
            $(".obHint").hide();
            $(".obHint_ON").show();
        };
        on = function() {
            //optionBuilder = new optionBuilderCopy("", disabledByText);

            optionBuilder.clear.createDelegate(optionBuilder)();
            onAuto();
        };
        off = function() {
            $.cookie("new_ob", 0);
            $(".obHint_ON").hide();
            $(".obHint").show();
            optionBuilder.deInit.createDelegate(optionBuilder)();
        };
        hide = function() {
            $.cookie("new_ob", -1);
            $(".obHint").fadeOut("slow");
        };

        $(document).ready(function() {

            $(".optionList table").prepend("<tr class='obHint' style='display:none;background-color:#CFCFCF;height: 1px;'><td colspan='10'></td></tr>");
            $(".optionList table").prepend("<tr class='obHint_ON' style='display:none;background-color:#CFCFCF;height: 1px;'><td colspan='10'></td></tr>");
            $(".optionList table").prepend("<tr class='obHint' style='display:none;background-color:#FFFFD6;'><td colspan=\"2\" style='padding: 10px'><a href='javascript:void(0)' onclick='on()' style='text-decoration: underline;color:black;'>"+lang.hint.on+"</a>" + lang.hint.onWarn + "</td><td colspan=\"3\" align='right' style='padding: 10px'><a href='javascript:void(0)' onclick='hide()' style='text-decoration: underline;'>"+lang.hint.hide+"</a></td></tr>");

            $(".optionList table").prepend("<tr class='obHint' style='display:none;background-color:#FFFFD6;border-bottom: 1px solid black;'><td style='padding: 10px;padding-bottom:0px;font-size:12px;color:black;' colspan=\"10\" align='center'>"+lang.hint.text+"</td></tr>");
            $(".optionList table").prepend("<tr class='obHint_ON' style='display:none;background-color:#FFFFD6;border-bottom: 1px solid black;'><td style='padding: 5px;padding-bottom:5px;font-size:12px;color:black;' colspan=\"10\" align='center'>"+lang.hint.text_on+"<a href='javascript:void(0)' onclick='off()' style='text-decoration: underline;font-size:11px;float:right;'>"+lang.hint.off+"</a></td></tr>");

            if(!$.cookie("new_ob") || $.cookie("new_ob") == 0) {
                show();
            } else if($.cookie("new_ob") == 1) {
                onAuto();
            } else {

            }

        });
        //$(document).ready(this.init.createDelegate(this));
    }


    this.rulesRepository = {
        codes : {},
        get: function(code) {
            var me = this;
            //d(me)
            if(!me.codes[code]) {
                me.codes[code] = new Rule(code);
                me.codes[code].doSelectHandler = meR.doSelectHandler;
                me.codes[code].doDeselectHandler = meR.doDeselectHandler;
                me.codes[code].disabledText = disabledText;
                me.codes[code].selectedText = selectedText;
                me.codes[code].deselectedText = deselectedText;
                me.codes[code].includedText = includedText;
                me.codes[code].idPrefix = idPrefix;
            }

            return me.codes[code];
        },

        findCodeMinimumPrice: function(codes, iterationCount) {
            var me = this;
            var currentCode = null;
            var price = null;

            if(!iterationCount) iterationCount = 1;

            $.each(codes, function(subI, subCode) {
                if(!currentCode) currentCode = subCode;

                var rule = me.ruleGet(subCode);

                var p = parseFloat(rule.getPriceWithChilds(iterationCount));
				
                if(p < price || price === null) {
                    price = p;
                    currentCode = subCode;
                }

                if(rule.selected) {
                    currentCode = subCode;
                    return false;
                }
            });

            return currentCode;
        }
    };
}

Rule = function(code) {
    this.code = code;
    this.rules = {
        Excludes: null,
        Requires: null,
        Includes: null
    };

    this.selected = 0;// user = 2, auto = 1

    this.disabled = false;
    this.disabledCodes = [];

    this.selectedBy = [];
    this.disabledBy = [];
    this.deselectedCodes = [];
}

var codeForSelectorProcess = function(code) {
    code = code + "";
    code = code.split("$").join("\\$");
	code = code.split("&").join("\\&");
    code = code.split("#").join("\\#");
    code = code.split("+").join("\\+");
    code = code.split("/").join("\\/");
	code = code.split(" ").join("\\ ");
	code = code.split(".").join("\\.");
    return code;
}

Rule.prototype = {
    getPriceWithChilds: function(iterationCount) {
        var me = this;

        var price = parseFloat(me.ClientPrice);		

        var ch = me.getChilds([], iterationCount);

		if (isExt) {
            Ext.each(ch, function(code) {
                var rulePrice = parseFloat(code.ClientPrice);
                price += isNaN(rulePrice) ? 0: rulePrice;
            })
        } else {
            $.each(ch, function(index, code) {
                var rulePrice = parseFloat(code.ClientPrice);
                price += isNaN(rulePrice) ? 0: rulePrice;
            })
		}
        return price;
    },

    getChilds: function(skip, iterationCount) {
        var me = this;
        var codesAll = [];
        var rules = me.rules;

        if(iterationCount > 5) {
            return codesAll;
        }

        if(skip.indexOf(me.code) > -1) {
            return codesAll;
        }

        skip.push(me.code);

        if(rules.Requires) {
            if(rules.Requires.type == "and") {
                $.each(rules.Requires.codes, function(i, code) {
                    if(!$.isString(code)) {
                        if(code.type == "or") {
                            var minCode = me.rulesRepository.findCodeMinimumPrice.createDelegate(me)(code.codes, iterationCount+1);
                            code = minCode;
                        }
                    }

                    var rule = me.ruleGet(code);
                    codesAll.push(rule);
                });
            }
            if(rules.Requires.type == "or") {
                var minCode = me.rulesRepository.findCodeMinimumPrice.createDelegate(me)(rules.Requires.codes, iterationCount+1);
                code = minCode;
                var rule = me.ruleGet(code);
                codesAll.push(rule.code);
            }
        }

        if(codesAll.length ==0) {
            return [];
        }

		if (isExt) {
            Ext.each(codesAll, function(co) {
                if(co.getChilds)
                    codesAll = codesAll.merge(co.getChilds(skip, iterationCount+1));
        });
		} else {
            $.each(codesAll, function(index, co) {
                if(co.getChilds)
                    codesAll = $.merge(codesAll, co.getChilds(skip, iterationCount+1));
        });
		}

        return codesAll;
    },

    addRule: function(type, rule) {
        var me = this;
        var rules;

        var andI = rule.indexOf("&");
        var orI = rule.indexOf("|");

        if(andI == -1 && orI == -1) {
            rules = { type:"and", codes:[rule] };
        }

        if(andI > 0 && orI == -1) {
            rules = { type:"and", codes:rule.split(" & ") };
        }

        if(orI > 0 && andI == -1) {
            rules = { type:"or", codes:rule.split(" | ") };
        }

        if(andI > 0 && orI > 0) {
            var e = rule.split(" & ");

            $.each(e, function(i,el) {
                if(el.indexOf("(") > -1) {
                    el = el.replace(/[()]/g, '').trim();
                    e[i] = { type:"or", codes:el.split(" | ") };
                }
            });

            rules = { type:"and", codes: e };
        }

        me.rules[type] = rules;
    },

    getText: function() {
        if(isExt) {
            var el = this.dom().parents("tr").children(".x-grid3-td-2").children(".x-grid3-cell-inner").justtext();
            return el;
        } else {
            var el = this.dom().parents("tr").children(".name").justtext();
            return el;

        }
        return this.code;
    },

    getTextInfo: function() {
        if(isExt) {
        } else {
            var el = $(".name .equip", this.dom().parents("tr")).html();
            return el;
        }
        return this.code;
    },

    getTextPrice: function() {
        if(isExt) {
        } else {
            var el = $(".clientPrice", this.dom().parents("tr")).html();
            return el;
        }
        return this.code;
    },

    isRadio: function() {
        return this.Type == "C" && this.Category == this.colorCategory;
    },

    dom: function() {
        //d("Sd")
        var code = this.code;
        //d(this.idPrefix+code)
        code = codeForSelectorProcess(code);

        return $("#"+this.idPrefix+code);
    },

    doDisable: function(byCode) {
        var me = this;


        if(byCode && me.disabledBy.indexOf(byCode) == -1) {
            me.disabledBy.push(byCode);
        }
        

        this.updateDisableText();
    },
    updateSelectedText: function() {
        var me = this;
        var html = this.selectedText + "";

        $("#selectedText_"+this.idPrefix+codeForSelectorProcess(me.code)).remove();
        $("#deselectedText_"+this.idPrefix+codeForSelectorProcess(me.code)).remove();


        if(!this.selectedBy.length) return;
        if(this.selectedBy.length == 1 && this.selectedBy[0] == -1) return;

        var texts = [];
        $.each(this.selectedBy, function(i, code) {
            if(!me.ruleGet) return;
            if(code < 0) return;
            var rule = me.ruleGet(code);
            texts.push("["+code+"] "+rule.getText());
        });

        if(isExt) {
            var el = this.dom().parents("tr").children(".x-grid3-td-2").children(".x-grid3-cell-inner");
        } else {
            var el = this.dom().parents("tr").children(".name");
        }

        $("#disabledText_"+this.idPrefix+codeForSelectorProcess(me.code)).remove();

        el.append(
            '<div id="selectedText_'+this.idPrefix+this.code+'" class="ob_element" style="display: block;color: #666666;font-size: 11px;'+(isExt?"":"padding-left: 20px;")+'">'+html+(texts.join(", "))+'</div>'
                );


    },

    updateIncludeText: function(code) {
        var me = this;
        var html = this.includedText + "";

        $("#disabledText_"+this.idPrefix+codeForSelectorProcess(me.code)).remove();

        var texts = [];
            var rule = me.ruleGet(code);
            texts.push("["+code+"] "+rule.getText());

        if(isExt) {
            var el = this.dom().parents("tr").children(".x-grid3-td-2").children(".x-grid3-cell-inner");
        } else {
            var el = this.dom().parents("tr").children(".name");
        }

        el.append(
            '<div id="disabledText_'+this.idPrefix+this.code+'" class="ob_element" style="display: block;color: #666666;font-size: 11px;'+(isExt?"":"padding-left: 20px;")+'">'+html+(texts.join(", "))+'</div>'
            );
    },

    updateDisableText: function() {

        var me = this;
        var html = this.disabledText + "";

        $("#disabledText_"+this.idPrefix+codeForSelectorProcess(me.code)).remove();

        this.disabled = false;
        this.dom().attr("disabled", false);

        if(!this.disabledBy.length) return;

        this.disabled = true;
        this.dom().attr("disabled", "disabled");

        var texts = [];
        $.each(this.disabledBy, function(i, code) {
            if(!me.ruleGet) return;
            var rule = me.ruleGet(code);
            texts.push("["+code+"] "+rule.getText());
        });

        if(isExt) {
            var el = this.dom().parents("tr").children(".x-grid3-td-2").children(".x-grid3-cell-inner");
        } else {
            var el = this.dom().parents("tr").children(".name");
        }

        el.append(
            '<div id="disabledText_'+this.idPrefix+this.code+'" class="ob_element" style="display: block;color: #666666;font-size: 11px;'+(isExt?"":"padding-left: 20px;")+'">'+html+(texts.join(", "))+'</div>'
            );

        me.updateSelectedText();
    },

    doEnable: function(byCode) {
        var me = this;
        me.disabledBy.remove(byCode);
        this.updateDisableText();
    },

    doSelect: function(byCode) {
        var me = this;

        if(me.selectedBy.indexOf(byCode) == -1) {
            me.selectedBy.push(byCode);
        }

        this.dom().attr("checked", true);



        if(this.selected != 2)
            this.selected = byCode === -1 ? 2 : 1;

        if(this.selected == 1) {
            me.disabledCodes.push(this.code);
            this.doDisable(byCode);
        }

        this.doSelectHandler(this.code, this.selected == 1);

        this.remakeAutoSelects(this.code);

        this.selectChilds();

        this.updateSelectedText();
    },



    remakeAutoSelects: function(byCode) {
        var me = this;
        //d(me)
        if(!me.rulesRepository) return;

        $.each(me.rulesRepository.codes, function(i, rule) {
            if(rule.selected == 1 ) { // auto selected
                $.each(rule.selectedBy, function(i2, code) {
                    var selectorRule = me.ruleGet(code);

                    var rules = selectorRule.rules;

                    if(rules.Requires) {
                        if(rules.Requires.type == "and") {
                            $.each(rules.Requires.codes, function(i, code) {
                                if(!$.isString(code)) {
                                    if(code.type == "or") {
                                        var rCodes = code.codes;
                                        if(rule.code != me.code && rCodes.indexOf(rule.code) > -1 && rCodes.indexOf(me.code) > -1) {
                                            me.deselectedCodes.push({code:rule.code,wasBy: code});
                                            rule.doDisable(me.code);
                                            rule.doDeselect(code);
                                        }
                                    }
                                }
                            });
                        }
                        if(rules.Requires.type == "or") {
                            var rCodes = rules.Requires.codes;
                            if(rule.code != me.code && rCodes.indexOf(rule.code) > -1 && rCodes.indexOf(me.code) > -1) {
                                //d(rule.code, me.code)
                                rule.doDisable(me.code);
                                me.deselectedCodes.push({code:rule.code,wasBy: code});
                                rule.doDeselect(code);
                            }
                        }
                    }
                });
            }
        });
    },

    doDeselect: function(byCode) {
        var me = this;

        this.selectedBy.remove(byCode);
        this.disabledBy.remove(byCode);

        if(this.selectedBy.length == 0 || (this.selectedBy.length == 1 && this.selectedBy[0] == -1)) {
            me.dom().attr("checked", false);
            me.dom().removeAttr("checked");

            this.selected = false;
        }

        if(this.disabledBy.length == 0) {
            me.doEnable();
        }

        $.each(me.disabledCodes, function(i, code) {
            var rule = me.ruleGet(code);
            rule.doEnable(me.code);
        });

        me.disabledCodes = [];

        this.doDeselectHandler(this.code);

        this.deselectChilds();

        if(me.deselectedCodes.length > 0) {
            $.each(me.deselectedCodes, function(i, info) {
                var rule = me.ruleGet(info.code);
                var wasRule = me.ruleGet(info.wasBy);
                if(wasRule.selected)
                    rule.doSelect(info.wasBy);
            });

            me.deselectedCodes = [];
        }

        //me.remakeAutoSelects(this.code);

        me.updateSelectedText();
    },

    updateState: function(byCode) {
        var me = this;

        this.selectedBy.remove(byCode);
        this.disabledBy.remove(byCode);

        if(this.disabledBy.length == 0) {
            me.doEnable();
        }

        me.updateSelectedText();
    },

    deselectChilds: function() {
        var me = this;
        var rules = me.rules;

        if(rules.Includes) {
            if(rules.Includes.type == "and") {
                $.each(rules.Includes.codes, function(i, code) {
                    var rule = me.ruleGet(code);

                    //d(me.code, code)
                    if(rule.selected) {
                        rule.doSelectHandler(rule.code);
                        rule.dom().attr("checked", true);
                    }

                });
            }
        }

        if(rules.Requires) {
            var internalDeselector = function(code) {
                var rule = me.ruleGet(code);

                if(rule.code && rule.selected == 1) {
                    rule.doDeselect(me.code);
                } else {
                    rule.updateState(me.code);
                }


            }
            if(rules.Requires.type == "and") {
                $.each(rules.Requires.codes, function(i, code) {
                    if(!$.isString(code)) {
                        if(code.type == "or") {
                            $.each(code.codes, function(subI, subCode) {
                                internalDeselector(subCode);
                            });
                        }
                    }

                    internalDeselector(code);
                });
            }
            if(rules.Requires.type == "or") {
                $.each(rules.Requires.codes, function(subI, subCode) {
                    internalDeselector(subCode);
                });
            }
        }

        if(rules.Excludes) {
            if(rules.Excludes.type == "and") {
                $.each(rules.Excludes.codes, function(i, code) {
                    var rule = me.ruleGet(code);
                    if(rule.isRadio()) return;

                    if(rule.selected) {
                        rule.doSelectHandler(rule.code);
                        rule.dom().attr("checked", true);
                    }
                });
            }
        }
    },

    selectChilds: function() {
        var me = this;
        var rules = me.rules;

        if(rules.Includes) {
            if(rules.Includes.type == "and") {
                $.each(rules.Includes.codes, function(i, code) {
                    var rule = me.ruleGet(code);

                    rule.disabledBy.push(me.code);
                    me.disabledCodes.push(code);
                    rule.doDisable(this.code);

                    rule.doDeselectHandler(rule.code);
                    rule.dom().removeAttr("checked");

                    rule.doDisable(this.code);
                    rule.updateIncludeText(me.code);
                });
            }
        }

        if(rules.Requires) {
            if(rules.Requires.type == "and") {
                $.each(rules.Requires.codes, function(i, code) {
                    if(!$.isString(code)) {
                        if(code.type == "or") {
                            var minCode = me.rulesRepository.findCodeMinimumPrice.createDelegate(me)(code.codes);
                            code = minCode;
                        }
                    }

                    var rule = me.ruleGet(code);
                    rule.selectedBy.push(me.code);

                    if(!rule.selected) {
                        rule.doSelect(me.code);
                    }

                    me.disabledCodes.push(me.code);

                    if(rule.selected != 2) {
                        rule.doDisable(me.code);
                    }

                });
            }
            if(rules.Requires.type == "or") {
                var minCode = me.rulesRepository.findCodeMinimumPrice.createDelegate(me)(rules.Requires.codes);
                code = minCode;
                var rule = me.ruleGet(code);

                if(rule.selectedBy.indexOf(me.code) == -1) {
                    rule.selectedBy.push(me.code);
                }

                if(!rule.selected) {
                    rule.doSelect(me.code);
                }

                me.disabledCodes.push(code);

                rule.doDisable(this.code);
            }
        }

        if(rules.Excludes) {
            if(rules.Excludes.type == "and") {
                $.each(rules.Excludes.codes, function(i, code) {
                    var rule = me.ruleGet(code);
                    if(rule.isRadio()) return;

                    me.disabledCodes.push(code);

                    rule.doDisable(me.code);

                    rule.doDeselectHandler(rule.code);
                    rule.dom().removeAttr("checked");
                });
            }
        }
    }
};

//ruleGet = rulesRepository.get;

optionBuilder.prototype = {
	colorCategory : isExt ? lang("Peinture") : optionBuilderColorCategory,
	_orderColor : null,
    stateOn: false,
	deInit: function() {
        var me = this;
        this.stateOn = false;

        $.each(me.rulesRepository.codes, function(code,v) {
			var rule = me.ruleGet(code);

            $(rule.dom()).removeAttr("disabled");
            $(".ob_element").remove();
        });
    },
    clear: function() {
        var me = this;

        $.each(me.rulesRepository.codes, function(code,v) {
			var rule = me.ruleGet(code);
            rule.deselectedCodes = [];
            rule.disabled = false;
            rule.disabledCodes = [];
            rule.selected = 0;
            rule.selectedBy = [];
            $(rule.dom()).removeAttr("checked");
            $(rule.dom()).removeAttr("disabled");
            $(".ob_element").remove();
        });
    },
	init: function() {
		var me = this;

        me.stateOn = true;

		if(!isExt) {
		//	initSubmiter();
		}
		if(!isExt && !me._orderColor) {
			me._orderColor = $("td.catName:contains('Peinture')").parents("tr");
		}

		$.each(me.rulesRepository.codes, function(code,v) {
			var rule = me.ruleGet(code);
						
			
            if(isExt) {
               $("#cont_" + me.idPrefix +  codeForSelectorProcess(code)).html(
                       '<input id="'+me.idPrefix+code+'" type="checkbox" />'
               );
            } else {
//                $("#" +  codeForSelectorProcess(code)).replaceWith(
//                       '<input id="'+me.idPrefix+code+'" value="'+code+'" name="options" type="checkbox" />'
//               );
            }

			var checkedBefore = $(rule.dom()).attr("checked");
			
            if(rule.isRadio()) {
                rule.dom().replaceWith("<input id='"+me.idPrefix+code+"' name=\""+(isExt?("Peinture_"+me.idPrefix):"options")+"\" value=\""+code+"\" type='radio' />");
				
                if(!isExt) {
					var tr = rule.dom().parents("tr");
                    tr.insertAfter(me._orderColor);
                    me._orderColor = rule.dom().parents("tr");
                }
            } else {
				
			}
			
			if(!isExt) {
				if(checkedBefore) {
					$(rule.dom()).attr("checked", true);
					rule.doSelect(-1);
				}
			}


            var dom = rule.dom();			
			dom.attr("disabled", false).removeAttr("disabled");			
            dom.click(me.checkBoxClick.createDelegate(me));	
			// return click handler from obSummary.js
			// because it's rewritten by rule.dom().replaceWith a few lines above
			if (rule.isRadio() && !isExt) {
				if (initSubmiter != undefined && updateClientPrice != undefined) {
					rule.dom().click(function() {
						updateClientPrice()
					});
				}
			}
		});		
	},

	ruleGet: function(code) {
        var me = this;
        return me.rulesRepository.get(code);
    },
	checkBoxClick: function(event) {
		var me = this;

        if(!me.stateOn) return;

        var rootCode = event.target.id;

        if(this.idPrefix != "") {
            rootCode = rootCode.substr(this.idPrefix.length);
        }

        var el = me.ruleGet(rootCode).dom();
		var type = el.attr("type");
		var chkd = el.attr("checked");

        var rule = me.ruleGet(rootCode);

		if(type == "radio")
		{			
			if(me.lastRadio) {
				if  (me.lastRadio != rootCode) {
					me.ruleGet(me.lastRadio).doDeselect(true);
				} else {
					// do nothing
					return;
				}
			}
			if(chkd)
				me.lastRadio = rootCode;
		}

		if(chkd) {
			rule.doSelect(-1);
		} else {
			rule.doDeselect(-1);
		}

		
	},

    doSelectHandler:function() {},
    doDeselectHandler:function() {},

	add: function(code, ruleText, rule_type, price, category, type) {
        var me = this;
        var rule = me.ruleGet(code);
        rule.ruleGet = me.ruleGet.createDelegate(me);
        rule.colorCategory = me.colorCategory;
        //d(me.rulesRepository)
        rule.rulesRepository = me.rulesRepository;
        rule.ClientPrice = price;
        rule.Type = type;
        rule.Category = category;

        if(rule_type && ruleText) {
            rule.addRule(rule_type, ruleText);
        }
	}
}

optionBuilderCopy = optionBuilder;

if(!isExt)
    optionBuilder = new optionBuilder("", disabledByText);

Array.prototype.remove = function(o){
	var index = this.indexOf(o);
	if(index != -1){
		this.splice(index, 1);
	}
	return this;
};
Array.prototype.indexOf = function(o, from){
	var len = this.length;
	from = from || 0;
	from += (from < 0) ? len : 0;
	for (; from < len; ++from){
		if(this[from] === o){
			return from;
		}
	}
	return -1;
};
	
String.prototype.trim = function(){
    var re = /^\s+|\s+$/g;
    return function(){ return this.replace(re, ""); };
}();

jQuery.isString = function(o)
{
    return (typeof o === "string");
}

jQuery.fn.justtext = function() {

    return $(this)  .clone()
            .children()
            .remove()
            .end()
            .text();

};

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
