function countArray(_array) {
    var count = 0;
    for(var i in _array) {
        count++;
    }
    return count;
}

var oBuynow = function()
{
    // PRIVATE VARIABLES
    var licensesPrices 			= new Array();
    var bundlesPrices 			= new Array();
    var offersPrices 			= new Array();
    var bundledProductsPrices 	= new Array();
    var licenses 				= new Array();
    var currencies2Operators 	= new Array();
    var currenciesRate			= new Array();
    var currency 				= 'USD';
    var language 				= 'en';
    var productVersion 			= '0';
    var productId 				= 0;
    var defaultOperatorId 		= 0;
    var currentOperatorId 		= 0;

    var selected 				= new Array();
    	selected['licenses'] 	= new Array();
    	selected['bundles']  	= new Array();
    	selected['offers']   	= new Array();

    var isCouponValid 			= false;

	var CouponLicenses			= new Array();
	var CouponPercent			= 0;
    var suppricesnotdiscount 	= new Array();	

    // Required fields
    var nameInput 		= new Array();
    var emailInput 		= new Array();

    // Total price
    var total 		= 0;
    
    // Total offers price
    var totalOffers = 0;

    // Prices for all selected items that was bilded after recalculate
    var supprices 	= new Array();

    // MAIN EMPLEMENTATION
    var publicObject = {

        setProductId: function(_productId)
        {
            productId = _productId;
        },

        setLanguage: function(_language)
        {
            language = _language;
        },

        setLicensesPrices: function(_licensesPrices)
        {
            licensesPrices = _licensesPrices;
        },

        setBundlesPrices: function(_bundlesPrices)
        {
            bundlesPrices = _bundlesPrices;
        },

        setOffersPrices: function(_offersPrices)
        {
            offersPrices = _offersPrices;
        },
        
        setCurrenciesRate: function(_currenciesRate)
        {
            currenciesRate = _currenciesRate;
        },
        
        

        setBundledProductsPrices: function(_bundledProductsPrices)
        {
            bundledProductsPrices = _bundledProductsPrices;
        },

        setLicenses: function(_licenses)
        {
            licenses = _licenses;
        },

        setProductVersion: function(_productVersion)
        {
            productVersion = _productVersion;
        },

        setLicenseQuantity: function(_licenseId, _quantity)
        {
            $('#lqn_' + _licenseId).val(_quantity);
            this.calculateTotal(_licenseId);
        },

        setDefaultOperatorId: function(_defaultOperatorId)
        {
            defaultOperatorId = _defaultOperatorId;
            currentOperatorId = _defaultOperatorId;
        },

        setCurrencies2Operators: function(_currencies2Operators)
        {
            currencies2Operators = _currencies2Operators;
        },

        showOffersPrices: function()
        {
            for(var i in offersPrices)
            {
            	if(total > 0)
            	{
                    $('#off_' + i).removeAttr('disabled');
                }
            	else
            	{
            		$('#off_' + i).attr('disabled', 'disabled');
            	//	delete(selected['offers'][i]);
                }

                var text = '';

                if(offersPrices[i]['text'])
                {
                    text = offersPrices[i]['text'];
                }
                else
                {
                    offersPrices[i]['text'] = text = $('#af' + i).html();
                }

                if(text != undefined && text.indexOf('XXX') != -1)
                {
                    if(offersPrices[i]['price_percent'] > 0)
                    {
                        if(total > 0)
                        {
                        	percPrice = publicObject.getOfferPercPrice(total, i, offersPrices[i]['price_percent']);
                        	
                            text = text.replace('XXX', currency + ' ' + percPrice);
                        }
                        else
                        {
                            text = text.replace('XXX', currency + ' ' + '0.00');
                        }
                    }
                    else
                    {
                        text = text.replace('XXX', currency + ' ' + offersPrices[i][currency]);
                    }
                }

                $('#af' + i).html(text);
            }
        },

        getOfferPercPrice: function(total, i, pricePercent)
        {
        	percPrice = ((total / 100) * pricePercent).toFixed(2);
        	
        	currRate = currenciesRate[currency];
        	
        	if(currRate == 0)
        	{
				currRate = 1;
			}
        	
        	if( i == 2  )
        	{
        		minpr = parseFloat((9.95 * currRate).toFixed(2));
        	
        		if(percPrice < minpr)
        		{       	
        			percPrice = minpr;
        		}	
        	}	
        	
        	if( i == 5 )
        	{
        		minpr = parseFloat((19.95 * currRate).toFixed(2));
	
        		if(percPrice < minpr)
        		{       	
        			percPrice = minpr;
        		}	
        	}	
        	
        	return parseFloat(percPrice);
        },
        
        setCurrency: function(_currency)
        {
            $('#' + currency.toLowerCase()).removeClass(currency.toLowerCase() + 'S');
            
            currency = _currency;
            
            $('#' + currency.toLowerCase()).addClass(currency.toLowerCase() + 'S');

            if(currencies2Operators[currency])
            {
                currentOperatorId = parseInt(currencies2Operators[currency]);
            }
            else
            {
                currentOperatorId = defaultOperatorId;
            }

            switch(currentOperatorId)
            {
                case 2:
                	$('#processButton').unbind('click');
                	$('#processButton').click(function()
                	{
                		publicObject.processPlimusOrder();
//                		publicObject.processElement5Order();
                		return false;
                	});
                	break;

                case 3:
                	$('#processButton').unbind('click');
                	$('#processButton').click(function() {
                		publicObject.processPlimusOrder();
                		return false;
                	});
                	break;
            }

            this.showPrices();
            this.showTotal();
            this.showOffersPrices();
            this.setCookie('currency', currency);
        },

        showPrices: function() {
            for(var i in licenses) {
                if(licensesPrices != undefined && licensesPrices[i] != undefined) {
                    $('#price_' + i).html(currency + ' ' + licensesPrices[i][currency]['price'].replace('.', '.<sup>') + '</sup>');

                    if(licensesPrices[i]['packs']) {
                        for(var j in licensesPrices[i]['packs']) {
                            $('#price_' + j).html(currency + ' ' + licensesPrices[i]['packs'][j][currency].replace('.', '.<sup>') + '</sup>');
                        }
                    }
                }
            }

            for(var i in bundlesPrices) {
                $('#bun_price_' + i).html('<s>' + currency + ' ' + bundledProductsPrices[i][currency].replace('.', '.<sup>') + '</sup></s> ' + currency + ' ' + bundlesPrices[i][currency]['price'].replace('.', '.<sup>') + '</sup>');
            }
        },

        showAllCurrencies: function() {
            $('#showAll').css('display', 'none');
            $('#hidedCurs').css('display', 'block');
        },

        closeNote: function() {
            $('#note').fadeOut('fast');
            this.setCookie('dontshownote', true);
        },

        placePurchaseOrder: function() {

            var paymentMethodInput = $(document.createElement('input'));
            paymentMethodInput.attr('type', 'hidden')
                              .attr('name', 'paymentMethod')
                              .val('po');

            this.processOrder(paymentMethodInput);
        },


        showTotal: function()
        {
            var subtotals 			= new Array();
			var subtotalsnotdiscount 			= new Array();
            var users 				= 0;
            var licenseSelectedFlag = false;
            var isInfinity 			= false;
			var subtotalEl;

            total 					= 0;
			totalnotdiscount		= 0;
            totalOffers 			= 0;

            for(var i in selected)
            {
                for(var j in selected[i])
                {
                    switch(i)
                    {
                        case 'licenses':
                    
                        	licenseSelectedFlag = true;

                            var price = parseFloat(licensesPrices[j][currency]['price']).toFixed(2);

                            if(selected[i][j] > 1 && licensesPrices[j]['packs'])
                            {
                                for(var k in licensesPrices[j]['packs'])
                                {
                                    var minUsers = parseInt(licensesPrices[j]['packs'][k]['min_usernumber']);
                                    var maxUsers = parseInt(licensesPrices[j]['packs'][k]['usernumber']);

                                    if(selected[i][j] >= minUsers && (selected[i][j] <= maxUsers || maxUsers == 0))
                                    {
                                        price = parseFloat(licensesPrices[j]['packs'][k][currency]).toFixed(2);
                                        break;
                                    }
                                }
                            }
							
		                    discount = (CouponLicenses[j] != undefined) ? CouponPercent : 0;
							pricenotdiscount =  price;
							price =  parseFloat(price * (1 - discount / 100)).toFixed(2);
							
	                   		subtotals[j] = selected[i][j] * price;
                    		subtotalsnotdiscount[j] = selected[i][j] * pricenotdiscount;	

                    		supprices[j] = pricenotdiscount;							
                    		suppricesnotdiscount[j] = pricenotdiscount;

                            total += subtotals[j];
							totalnotdiscount	+= subtotalsnotdiscount[j];
							
							var usersInLicense = parseInt(licenses[j]['users_in_license']);
                            users += selected[i][j] * usersInLicense;
							
                            break;

                        case 'bundles':
                       		total += selected[i][j] * parseFloat(bundlesPrices[j][currency]["price"]);
							totalnotdiscount += selected[i][j] * parseFloat(bundlesPrices[j][currency]["price"]);
                            break;
                    }
                }
            }

            if(total > 0)
            {
                for(var i in selected['offers'])
                {
                    if(offersPrices[i]['price_percent'] > 0)
                    {
                    	percPrice = publicObject.getOfferPercPrice(total, i, offersPrices[i]['price_percent']);
                    	
                        totalOffers += percPrice;
                    }
                    else
                    {
                        totalOffers += parseFloat(offersPrices[i][currency]);
                    }
                }
            }

            for(var i in licensesPrices)
            {
            	subtotalEl = $("#subtotal_" + i);
				if (subtotals[i])
            	{
            		
					subtotalEl.html(subtotals[i].toFixed(2).replace(".", ".<sup>") + "</sup>");
					if (CouponLicenses[i] != undefined && CouponPercent > 0){
						subtotalEl.addClass('discount');
					}else{
						subtotalEl.removeClass('discount');
					}
            	}
            	else
            	{
            		subtotalEl.html("0.<sup>00</sup>").removeClass('discount');
                }
            }
 
 		    $("#total_right").html(currency + " " + (total + totalOffers).toFixed(2).replace(".", ".<sup>") + "</sup>");
			if ( total < totalnotdiscount){
				$("#total_right").addClass('colorred');	
	            $("#total_bottom").html(currency + " <s>" + (totalnotdiscount + totalOffers).toFixed(2).replace(".", ".<sup>") + "</sup></s> <b class='colorred'>"+(total + totalOffers).toFixed(2).replace(".", ".<sup>") + "</sup></b>");
			}else{
				$("#total_right").removeClass('colorred');	
	            $("#total_bottom").html(currency + " " + (total + totalOffers).toFixed(2).replace(".", ".<sup>") + "</sup>");				
			}
            $("#usernumber_right").html((isInfinity ? "&infin;": users.toString()));
            
/*            $('#total_bottom').html(currency + ' ' + (total + totalOffers).toFixed(2).replace('.', '.<sup>') + '</sup>');
            $('#total_right') .html(currency + ' ' + (total + totalOffers).toFixed(2).replace('.', '.<sup>') + '</sup>');
            $('#usernumber_right').html((isInfinity ? '&infin;' : users.toString()));*/
        },

		processPlimusOrder : function(additionalField)
		{
			var processForm = $(document.createElement("form"));
		
			processForm	.attr("action", "https://www.plimus.com/jsp/buynow.jsp")
						.attr("method", "post");
			
			var counter = 0;
			
			if (countArray(selected.licenses) == 0)
			{
				for ( var i in licenses)
				{
					if (licenses[i]["default"] == "Y")
					{
						selected.licenses[licenses[i]["id"]] = 1;
						break
					}
				}
			}
			
			for ( var i in selected)
			{
				for ( var j in selected[i])
				{
					if (counter == 0)
					{
						var contractIdInput 	= $(document.createElement("input"));
							contractIdInput		.attr("type", "hidden")
												.attr("name", "contractId")												;

						var overridePrice 		= $(document.createElement("input"));
							overridePrice		.attr("type", "hidden")
												.attr("name", "overridePrice");
						
						var quantity 			= $(document.createElement("input"));
							quantity			.attr("type", "hidden")
												.attr("name", "quantity")
												.val(selected[i][j]);
							
						if (i == "licenses")
						{
							if (licensesPrices[j][currentOperatorId]["contractIds"][currency])
							{
								contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"][currency]);
							}
							else
							{
								contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"]["default"]);
							}
							overridePrice.val(supprices[j]);
						}

						if (i == "bundles")
						{
							if (bundlesPrices[j][currentOperatorId]["contractIds"][currency])
							{
								contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"][currency]);
							}
							else
							{
								contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"]["default"]);
							}
							
							overridePrice	.val((parseFloat(bundlesPrices[j][currency]["price"]))
											.toFixed(2));
						}
						
						if (i == "offers")
						{
							if (offersPrices[j][currentOperatorId][currency])
							{
								contractIdInput.val(offersPrices[j][currentOperatorId][currency]);
							}
							else
							{
								contractIdInput.val(offersPrices[j][currentOperatorId]["USD"]);
							}
							
							if (offersPrices[j]["price_percent"] > 0)
							{
								percPrice = publicObject.getOfferPercPrice(total, j, offersPrices[j]['price_percent']);
								overridePrice.val( percPrice );
							}
							overridePrice.val(offersPrices[j]["price"]);
						}
						
						processForm	.append( contractIdInput )
									.append( overridePrice )
									.append( quantity );
					}
					else
					{
						var contractIdInput 	= $(document.createElement("input"));
							contractIdInput		.attr("type", "hidden")
												.attr("name", "promoteContractId" + (counter - 1));
	
						var contractFlagInput 	= $(document.createElement("input"));
							contractFlagInput	.attr("type", "hidden")
												.attr("name", "promoteContractFlag" + (counter - 1))
												.val("Y");
						
						var contractAddInput 	= $(document.createElement("input"));
							contractAddInput	.attr("type", "hidden")
												.attr("name", "addPromoteContract" + (counter - 1))
												.val("Y");

						
						var overridePrice 		= $(document.createElement("input"));
							overridePrice		.attr("type", "hidden")
												.attr("name", "promoteOverridePrice" + (counter - 1));
					
						var quantity 			= $(document.createElement("input"));
							quantity			.attr("type", "hidden")
												.attr("name", "promoteQuantity" + (counter - 1))
												.val(selected[i][j]);

						if (i == "licenses")
						{
							if (licensesPrices[j][currentOperatorId]["contractIds"][currency])
							{
								contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"][currency]);
							}
							else
							{
								contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"]["default"]);
							}
							overridePrice.val(supprices[j]);
						}

						if (i == "bundles")
						{
							if (bundlesPrices[j][currentOperatorId]["contractIds"][currency])
							{
								contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"][currency]);
							}
							else
							{
								contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"]["default"]);
							}
							
							overridePrice	.val((parseFloat(bundlesPrices[j][currency]["price"]))
											.toFixed(2));
						}

						if (i == "offers")
						{
							if (offersPrices[j][currentOperatorId][currency])
							{
								contractIdInput.val(offersPrices[j][currentOperatorId][currency]);
							}
							else
							{
								contractIdInput.val(offersPrices[j][currentOperatorId]["USD"]);
							}
							
							if (offersPrices[j]["price_percent"] > 0)
							{
								percPrice = publicObject.getOfferPercPrice(total, j, offersPrices[j]['price_percent']);
								overridePrice.val( percPrice );												
							}
							
							overridePrice.val(offersPrices[j]["price"]);
						}

						processForm	.append(contractIdInput)
									.append(contractFlagInput)
									.append(contractAddInput)
									.append(overridePrice)
									.append(quantity);
					}
					counter++;
				}
			}
			
			if (counter > 1)
			{
				var numberOfPromotionContractsInput = $(document.createElement("input"));
				
				numberOfPromotionContractsInput	.attr("type", "hidden")
												.attr("name", "numberOfPromotionContract")
												.val(counter - 1)
												.appendTo(processForm);
			}
			
			var bcurInput = $(document.createElement("input"));
				bcurInput	.attr("type", "hidden")
							.attr("name", "bCur")
							.val(currency)
							.appendTo(processForm);
			
			var currencyInput = $(document.createElement("input"));
				currencyInput	.attr("type", "hidden")
								.attr("name", "currency")
								.val(currency)
								.appendTo(processForm);
			
			var languageInput = $(document.createElement("input"));
				languageInput	.attr("type", "hidden")
								.attr("name", "language");
			
			if (language == "en")
			{
				languageInput.val("ENGLISH");
			}
			
			if (language == "fr")
			{
				languageInput.val("FRENCH")
			}
			
			if (language == "de")
			{
				languageInput.val("GERMAN")
			}
			
			languageInput.appendTo(processForm);
			
			var couponInput = $(document.createElement("input"));
				couponInput	.attr("type", "hidden")
							.attr("name", "couponCode")
							.val($("#coupon_input").val())
							.appendTo(processForm);
			
			var templateId = $(document.createElement("input"));
				templateId	.attr("type", "hidden")
							.attr("name", "templateId")
							.val($("#templateId").val())
							.appendTo(processForm);
				
			if (additionalField)
			{
				processForm.append(additionalField)
			}
			
			processForm.appendTo(document.body);
			
			var formPostData 	= processForm.formSerialize();
			
			
			var procButton 		= $("#processButton");
			
			procButton.val($("#please_wait").html());
			procButton.attr("disabled", "disabled");
			
			processForm.submit()
		},
        
        calculateTotal: function(_licenseId, _bundleId, _offerId)
        {
        	
            if(_licenseId != undefined)
            {
                var checked 	= $('#lic_' + _licenseId).is(':checked');
                var quantity 	= $('#lqn_' + _licenseId).val();

                if(checked)
                {
                    if(!isNaN(quantity))
                    {
                        selected['licenses'][_licenseId] = quantity;
                    }
                }
                else
                {
                    delete(selected['licenses'][_licenseId]);
                }
            }

            if(_bundleId != undefined)
            {
                var checked 	= $('#bun_' + _bundleId).is(':checked');
                var quantity 	= $('#bqn_' + _bundleId).val();

                if(checked)
                {
                    if(!isNaN(quantity))
                    {
                        selected['bundles'][_bundleId] = quantity;
                    }
                }
                else
                {
                    delete(selected['bundles'][_bundleId]);
                }
            }

            if(_offerId != undefined)
            {
           		if(_offerId == 4)
           		{
           			selected['offers'][_offerId] = true;
           			delete(selected['offers'][5]);
           		}

           		if(_offerId == 5)
           		{
           			selected['offers'][_offerId] = true;
           			delete(selected['offers'][4]);
           		}

           		if(_offerId == 2)
           		{
           			selected['offers'][_offerId] = true;
           		}

           		if(_offerId == '0')
           		{
           			delete(selected['offers'][4]);
           			delete(selected['offers'][5]);
           		}

           		if(_offerId == -1)
           		{
           			delete(selected['offers'][2]);
           		}
            }
            
/*            this.showTotal();
            this.showOffersPrices();
            this.checkCoupon();*/
		
          	this.checkCoupon()            
          	this.showOffersPrices();
        },

/*        checkCoupon: function() {

            var coupon = $('#coupon_input').val();
            var status = $('#couponStatus');
            var licensesStr = '';

            for(var i in selected['licenses']) {
                licensesStr += (licensesStr != '' ? ',' : '') + i;
            }

            status.html('');

            if(coupon.length > 0 && licensesStr.length > 0) {

                status.html('<img src="/images/buynow/spinner_white.gif" width="24" height="24" style="margin-left:5px;" />');
                ajax.post('/jcontroller/index.php', 'ajaxmethod=validatecoupon&coupon=' + encodeURIComponent(coupon) + '&licenses=' + licensesStr, {'func': 'oBuynow.checkCouponSucc'});
            }
        },

        checkCouponSucc: function(value) {

            var status = $('#couponStatus');

            if(parseInt(value) == 0 || value == '' ) {
                status.html('<div class="notValid">' + $('#not_valid').html() + '</div>');
                isCouponValid = false;
            } else {
                status.html('<div class="valid">OK!</div>');
                isCouponValid = true;
            }
        },*/

        checkCoupon: function()
        {
		    var coupon 		= $("#coupon_input").val();
            var status 		= $("#couponStatus");
            var licensesStr = "";
			CouponPercent = 0;
			CouponLicenses = new Array();            
			coupon = coupon.replace(/(^\s+)|(\s+$)/g, "");
            
			for (var i in selected.licenses)
            {
                licensesStr += (licensesStr != "" ? ",": "") + i
            }
            status.html("");
            
            if (coupon.length > 0 && licensesStr.length > 0)
            {
                status.html('<img src="/images/buynow/spinner_white.gif" width="24" height="24" style="margin-left:5px;" />');
				$.ajax({
						type: 'POST',
						url: "/jcontroller/index.php",
						dataType: 'json',
//						data: "ajaxmethod=validatecoupon&coupon=" + encodeURIComponent(coupon) + "&licenses=" + licensesStr + '&operator=' + currentOperatorId,
						data: "ajaxmethod=validatecoupon&coupon=" + encodeURIComponent(coupon) + "&licenses=" + licensesStr,						
						success: function(data){oBuynow.checkCouponSucc(data);
												oBuynow.showTotal();}
						});
            }else{
				oBuynow.showTotal();
			}
        },
		
        checkCouponSucc: function(value) {
            var status = $("#couponStatus");
			
			if (value.percent != undefined){
				CouponPercent = value.percent;
			}
			if (value.licenses != undefined){
						CouponLicenses = value.licenses;
			}
            if (parseInt(CouponPercent) > 0 && countArray(CouponLicenses) > 0) {
				if ($('#discount_succ_text').html() == null){
	                status.html('<div class="valid">OK!</div>');
				}else{
					status.html('<div class="valid">'+CouponPercent.replace('"','').replace('"','')+'% '+$('#discount_succ_text').html()+'</div>');	
				}
                isCouponValid = true
            } else {
                status.html('<div class="notValid">' + $("#not_valid").html() + "</div>");
                isCouponValid = false
            }
        },

        checkWhoyouareInfo: function() {

            var errors = false;

            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

            if(nameInput['input'].val() == nameInput['default']) {
                nameInput['input'].css('color', '#d00');
                errors = true;
            } else {
                nameInput['input'].css('color', '#000');
            }

            emailInput['input'].css('color', '#000');

            if(emailInput['input'].val() == emailInput['default'] || !reg.test(emailInput['input'].val())) {
                emailInput['input'].css('color', '#d00');
                errors = true;
            }

            if(errors) {
                $('#whoyouareStatus').html('<div class="notValid">' + $('#not_valid').html() + '</div>');
                return false;
            } else {
                $('#whoyouareStatus').html('<div class="valid">OK!</div>');
                return true;
            }
        },

        setCookie: function(cookieName, value) {
            var exdate = new Date();
            exdate.setDate(365);
            document.cookie = cookieName + '=' + escape(value)+ ';path=/' + ';expires=' + exdate + ';domain=' + location.host;
        },

        getCookie: function(cookieName) {

            if (document.cookie.length > 0) {

                start = document.cookie.indexOf(cookieName + '=');

                if (start != -1) {

                    start = start + cookieName.length + 1 ;
                    end = document.cookie.indexOf(";", start);

                    if (end == -1) {
                        end = document.cookie.length;
                    }
                    return unescape(document.cookie.substring(start, end));
                }
            }
            return null;
        }
    }

    // PRIVATE METHODS

    $(document).ready(function() {
    	
		$('a').filter(function () { return (/\.(exe|dmg|apk|zip|rar|bz2)(?:\?([^#]*))?(?:#(\.*))?$/i.test($(this).attr('href'))) && ($(this).attr('notrack') == undefined); }).bind('click', function(){_gaq.push(['_trackPageview',$(this).attr('href')])});
	var licLinks = $(".license");	
		$.each(licLinks, function(){this.href = this.href + '?ajax=true';$(this).colorbox({iframe:true, innerWidth:'80%', innerHeight:'70%', speed:200,opacity:0.8});});
    	publicObject.showOffersPrices();
    	
    	var offRadio = $(".offRadio");
    	
    	offRadio.removeAttr("disabled");
    	
    	offRadio.click(function()
    	{
    		offRadioVal = this.value;
    		publicObject.calculateTotal(null,null,offRadioVal);
    	});
    	
        var userCurrency = publicObject.getCookie('currency');
        
        if(userCurrency != null && userCurrency != 'USD')
        {
            publicObject.setCurrency(userCurrency);
        }
        else
        {
            if(window.location.toString().indexOf('/fr/') != -1 ||
               window.location.toString().indexOf('/de/') != -1)
            {
                publicObject.setCurrency('EUR');
            }
            else
            {
                publicObject.setCurrency('USD');
            }
        }

        var spinButtons = $("input.inpText").SpinButton({min:1, reset:1});

        var onChangeQuantity = function()
        {
            var id 		= $(this).attr('id').substring(4);
            var type 	= $(this).attr('id').substring(0, 3);

            switch(type)
            {
            	case 'lqn':
                    if(!$('#lic_' + id).is(':checked'))
                    {
                        $('#lic_' + id).attr('checked', 'checked');
                    }
                    publicObject.calculateTotal(id, null, null);
                    break;
                
            	case 'bqn':
                    if(!$('#bun_' + id).is(':checked'))
                    {
                        $('#bun_' + id).attr('checked', 'checked');
                    }
                    publicObject.calculateTotal(null, id, null);
                    break;
            }
        };

        var onChangeQuantityForBetatesters = function()
        {
            var id 		= $(this).attr('id').substring(4);
            var type 	= $(this).attr('id').substring(0, 3);

            switch(type)
            {
                case 'lqn':
                    publicObject.calculateTotal(id, null, null);
                    break;
                
                case 'bqn':
                    publicObject.calculateTotal(null, id, null);
                    break;
            }
        };

        if(currencies2Operators[currency])
        {
            currentOperatorId = parseInt(currencies2Operators[currency]);
        }
        else
        {
            currentOperatorId = defaultOperatorId;
        }

        switch(currentOperatorId)
        {
            case 2:
            $('#processButton').unbind('click');
            $('#processButton').click(function()
           	{
//            	publicObject.processElement5Order();
           		publicObject.processPlimusOrder();
                return false;
            });
            break;

            case 3:
            	$('#processButton').unbind('click');
            	$('#processButton').click(function() {
            		publicObject.processPlimusOrder();
            		return false;
            	});
            	break;
        }

        spinButtons.bind("mousewheel", onChangeQuantityForBetatesters);
        spinButtons.bind("change", onChangeQuantity);
        spinButtons.mouseup(onChangeQuantity);

        setTimeout(function()
        {
            $('#mainForm').resetForm();

            for(var i in licensesPrices)
            {
                publicObject.calculateTotal(i);
            }

            for(var i in bundlesPrices)
            {
                publicObject.calculateTotal(null, i);
            }

            selected['licenses'] = new Array();

            for(var i in licenses)
            {
                if(licenses[i]['default'] == 'Y')
                {
                    $('#lic_' + licenses[i]['id']).attr('checked', 'checked');
                    publicObject.calculateTotal(licenses[i]['id']);
                    break;
                }
            }

        }, 100);

        $('.e-button').bind('click', function() {
            var link = $(this);
            link.removeClass('e-button-p');
            link.addClass('e-button');
        });

        $('.e-button').bind('mousedown', function() {
            var link = $(this);
            link.removeClass('e-button');
            link.addClass('e-button-p');
        });

        $('.e-button').bind('mouseup', function() {
            var link = $(this);
            link.removeClass('e-button-p');
            link.addClass('e-button');
        });

        $('.e-button').bind('mouseout', function() {
            var link = $(this);
            link.removeClass('e-button-p');
            link.addClass('e-button');
        });
    });

    return publicObject;
}();


