function countArray(B) {
    var C = 0;
    for (var A in B) {
        C++;
    }
    return C;
} 

var oBuynow = function() {
    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 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 nameInput 				= new Array();
    var emailInput 				= new Array();
    var total 					= 0;
    var totalOffers 			= 0;
    var supprices 				= new Array();

	var CouponLicenses			= new Array();
	var CouponPercent			= 0;
    var suppricesnotdiscount 	= new Array();	

	var dele 	;
	var selecOp;
	var af5;
	var af7;

	

    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;
        },
		
        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;
		},

		setCurrentOperatorId: function(_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);
        	
        	if(i == 2 && percPrice < publicObject.getCurConvert(9.95) )
        	{
        		percPrice = publicObject.getCurConvert(9.95);
        	}	

        	if(i == 5 || i == 7 )
        	{
        		maxPrice = publicObject.getMaxPriceFromSelected();
        		
        		var premium = $("#af5");
        		var priority = $("#af7");

		//		var dele 	= $("#dele");
//				var selecOp = $("#selecOp");

        		if( i == 5 )
        		{
           			if( maxPrice > publicObject.getCurConvert( 5 ) )
               		{
						priority.removeAttr("selected");
           				
           				priority.css("display","none");
           				dele.append(priority);
           				
           				premium.css("display","block");
           				selecOp.append(premium);
						
           				if(selected.offers[7])
           				{	
           					publicObject.calculateTotal(null, null, 4);
           					delete(selected.offers[7]);
           				}	
               		}	
        		}
        		

        		if( i == 7 )
        		{
           			if( maxPrice <= publicObject.getCurConvert( 5 ) )
               		{
           				premium.removeAttr("selected");
           				
           				premium.css("display","none");
           				dele.append(premium);
           				
           				priority.css("display","block");
           				selecOp.append(priority);
						
           				if(selected.offers[5])
           				{	
           					publicObject.calculateTotal(null, null, 4);
           					delete(selected.offers[5]);
           				}	

           				
            			if( maxPrice >= publicObject.getCurConvert( 7 ) )
            			{
            				priceAf5 = publicObject.getCurConvert( 5 ); // 150 $
            				usdToCur = priceAf5/150; 
            				percPrice = usdToCur * 29.95;
            			}
            			else
            			{
            				priceAf5 = publicObject.getCurConvert( 5 ); // 150 $
            				usdToCur = priceAf5/150; 
            				percPrice = usdToCur * 19.95;
            			}
               		}	
        		}	
        	}
        	return parseFloat(percPrice).toFixed(2);
        },
        
        getCurConvert: function(offId)
        {
        	if(offersPrices[offId])
        	{	
	        	
	       		if(offersPrices[offId][currency])
	       		{
	       			return parseInt(offersPrices[offId][currency]);
	       		}
	       		else
	       		{
	       			return parseInt(offersPrices[offId]['USD']);
	       		}
        	}	
        },
        
        getMaxPriceFromSelected: function ()
        {
        	var maxPrice = 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( parseInt(maxPrice) < parseInt(price))
                    		{
                    			maxPrice = parseInt(price);
                    		}	
                    		break;
                    }
                }
            }
        	return maxPrice;
        },
        
        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.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 &&
						licensesPrices[i][currency] != 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)
        },
        changeUpgradeNowLink: function(select)
        {
        	var version = $(select).val();

            if (parseInt(productVersion) == parseInt(version))
            {
            	$("#upgrade_link").colorbox({
                    width: "50%",
                    inline: true,
                    href: "#upgrade_info_container p",
                    opacity: 0.8
                });
            }
            else
            {
            	$("#upgrade_link").unbind($.cbox_click)
                .removeClass("cboxElement");
            }
        },
        
        expandCollapse: function(elementId, link)
        {
            var elem = $("#" + elementId);
            if (elem.css("display") == "none")
            {
                elem.slideDown("fast");
                if (link != undefined)
                {
                    $(link).attr("class", $(link).attr("class").replace(" close", ""));
                }
            }
            else
            {
            	elem.slideUp("fast");
                if (link != undefined)
                {
                	$(link).attr("class", $(link).attr("class") + " close");
                }
            }
        },
        
        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];
//                    		users 		+= selected[i][j] * parseInt(licenses[j]["usernumber"]); //rjon76 16.09.2010
                    		users 		+= selected[i][j] * parseInt(licenses[j]["users_in_license"]); //rjon76 16.09.2010

                        
                    		if (parseInt(licenses[j]["usernumber"]) == 0)
                    		{
                    			isInfinity = true
                    		}
                    		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)
            	{
            		//alert(i);
            		if (offersPrices[i]["price_percent"] > 0)
            		{
                       	percPrice = publicObject.getOfferPercPrice(total, i, offersPrices[i]['price_percent']);
                       	
                       	totalOffers += parseFloat(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 (i == "offers" && offersPrices[j][currentOperatorId]["contract_id"] == "backupcd")
                    {
                        var addCDInput = $(document.createElement("input"));
                        	addCDInput.attr("type", "hidden").attr("name", "addCD").val("Y").appendTo(processForm)
                    }
                    else
                    {
                    	if (counter == 0)
                    	{
                            var contractIdInput	= $(document.createElement("input"));
                            var overridePrice	= $(document.createElement("input"));
                            var quantity		= $(document.createElement("input"));
                            
                            contractIdInput.attr("type", "hidden").attr("name", "contractId");
                            
                            if (i == "licenses")
                            {
                                if (licensesPrices[j][currentOperatorId]["contractIds"][currency])
                                {
                                    contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"][currency])
                                }
                                else
                                {
                                	contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"]["default"])
                                }
                            }
                            else
                            {
                            	if (i == "bundles")
                            	{
                            		if (bundlesPrices[j][currentOperatorId]["contractIds"][currency])
                            		{
                                        contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"][currency])
                            		}
                            		else
                            		{
                            			contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"]["default"])
                            		}
                                }
                            	else
                            	{
                            		if (i == "offers")
                            		{
                            			if (offersPrices[j][currentOperatorId][currency])
                            			{
                            				contractIdInput.val(offersPrices[j][currentOperatorId][currency])
                            			}
                            			else
                            			{
                            				contractIdInput.val(offersPrices[j][currentOperatorId]["USD"])
                            			}
                                    }
                                }
                            }
                            
                            quantity.attr("type", "hidden").attr("name", "quantity").val(selected[i][j]);
                            overridePrice.attr("type", "hidden").attr("name", "overridePrice");
                            
                            if (i == "licenses")
                            {
                            	overridePrice.val(supprices[j])
                            }
                            else
                            {
                            	if (i == "bundles")
                            	{
                            		overridePrice.val((parseFloat(bundlesPrices[j][currency]["price"])).toFixed(2))
                            	}
                            	else
                            	{
                            		if (i == "offers")
                            		{
                            			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"));
                            var contractFlagInput 	= $(document.createElement("input"));
                            var contractAddInput	= $(document.createElement("input"));
                            var overridePrice 		= $(document.createElement("input"));
                            var quantity 			= $(document.createElement("input"));
                            contractIdInput.attr("type", "hidden").attr("name", "promoteContractId" + (counter - 1));
                            
                            if (i == "licenses")
                            {
                                if (licensesPrices[j][currentOperatorId]["contractIds"][currency])
                                {
                                    contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"][currency])
                                }
                                else
                                {
                                	contractIdInput.val(licensesPrices[j][currentOperatorId]["contractIds"]["default"])
                                }
                            }
                            else
                            {
                            	if (i == "bundles")
                            	{
                                    if (bundlesPrices[j][currentOperatorId]["contractIds"][currency])
                                    {
                                        contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"][currency])
                                    }
                                    else
                                    {
                                        contractIdInput.val(bundlesPrices[j][currentOperatorId]["contractIds"]["default"])
                                    }
                                }
                            	else
                            	{
                            		if (i == "offers")
                            		{
                                        if (offersPrices[j][currentOperatorId][currency])
                                        {
                                            contractIdInput.val(offersPrices[j][currentOperatorId][currency])
                                        }
                                        else
                                        {
                                        	contractIdInput.val(offersPrices[j][currentOperatorId]["USD"])
                                        }
                                    }
                                }
                            }
                            
                            contractFlagInput.attr("type", "hidden").attr("name", "promoteContractFlag" + (counter - 1)).val("Y");
                            contractAddInput.attr("type", "hidden").attr("name", "addPromoteContract" + (counter - 1)).val("Y");
                            overridePrice.attr("type", "hidden").attr("name", "promoteOverridePrice" + (counter - 1));
                            
                            if (i == "licenses")
                            {
                            	overridePrice.val(supprices[j])
                            }
                            else
                            {
                            	if (i == "bundles") {
                            		overridePrice.val((parseFloat(bundlesPrices[j][currency]["price"])).toFixed(2))
                            	}
                            	else
                            	{
                            		if (i == "offers")
                            		{
                            			if (offersPrices[j]["price_percent"] > 0)
                            			{
                            				percPrice = publicObject.getOfferPercPrice(total, j, offersPrices[j]["price_percent"]);
                            				overridePrice.val(percPrice);
                            			}
                                        
                            			overridePrice.val(offersPrices[j]["price"])
                            		}
                                }
                            }
                            
                            quantity.attr("type", "hidden").attr("name", "promoteQuantity" + (counter - 1)).val(selected[i][j]);
                            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")
            }
            else
            {
                if (language == "fr")
                {
                	languageInput.val("FRENCH")
                }
                else
                {
                    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);
            
            if (additionalField)
            {
                processForm.append(additionalField)
            }
			processForm.bind('submit', function(){ 
					if (window.pageTracker !== undefined)
							{
								pageTracker._linkByPost(this, true);
								
							};

						})	
            processForm.appendTo(document.body);
            var formPostData 	= processForm.formSerialize();
            var procButton 		= $("#processButton");
            	procButton.val($("#please_wait").html());
            	procButton.attr("disabled", "disabled");
	           ajax.post("/jcontroller/index.php", formPostData + "&productId=" + productId + "&ajaxmethod=processOrder", function(response) {
               processForm.submit()
            })
        },
			
		/*
			PROCESS ELEMENT 5
		*/
		
		processElement5Order: function (additionalField)
		{
            	
            this.calculateTotal();	
			var element5link 	= "";
			var offersData 		= new Array();
			element5link 		+= "currencies=" + currency;
			
			if (language == "en")
			{
				element5link += "&languageid=1"
			}
			else
			{
				if (language == "fr")
				{
					element5link += "&languageid=6"
				}
				else
				{
					if (language == "de")
					{
						element5link += "&languageid=2"
					}
				}
			}

			var escapeOrig = window.escape;

			window.escape = function (str)
			{
				var ret = [];
				for (var i = 0; i < str.length; i++)
				{
					var n = str.charCodeAt(i);
					if (n <= 0xFF)
					{
						ret.push(n);
					}	
				}
				return escapeOrig(String.fromCharCode.apply(null, ret));
			}

			if (isCouponValid)
				element5link += "&COUPON1=" + escape($("#coupon_input").val());

			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])
				{
					element5link += "&PRODUCT[";
				
					var contractId = "";
					
					if (i == "licenses")
					{
						if (licensesPrices[j][currentOperatorId]["contractIds"][currency])
						{
							contractId += licensesPrices[j][currentOperatorId]["contractIds"][currency]
						}
						else
						{
							contractId += licensesPrices[j][currentOperatorId]["contractIds"]["default"]
						}
					}
					else
					{
						if (i == "bundles")
						{
							if (bundlesPrices[j][currentOperatorId]["contractIds"][currency])
							{
								contractId += bundlesPrices[j][currentOperatorId]["contractIds"][currency]
							}
							else
							{
								contractId += bundlesPrices[j][currentOperatorId]["contractIds"]["default"]
							}
						}
						else
						{
							if (i == "offers")
							{
								if (offersPrices[j][currentOperatorId][currency])
								{
									contractId += offersPrices[j][currentOperatorId][currency]
								}
								else
								{
									contractId += offersPrices[j][currentOperatorId]["USD"]
								}
							}
						}
					}
					
					element5link += contractId + "]=" + (i == "offers" ? 1 : selected[i][j]);
					element5link += "&PRODUCTPRICE[" + contractId + "]=";
					
					if (i == "licenses")
					{
						element5link += supprices[j]
					}
					else
					{
						if (i == "bundles")
						{
							element5link += (parseFloat(bundlesPrices[j][currency]["price"])).toFixed(2)
						}
						else
						{
							if (i == "offers")
							{
								if (offersPrices[j]["price_percent"] > 0)
								{
									percPrice = publicObject.getOfferPercPrice(total, j, offersPrices[j]["price_percent"]);
									
									element5link += offersData[contractId] = percPrice;
								}
								else
								{
									element5link += offersPrices[j][currency]
								}
							}
						}
					}
					
					element5link += currency + ",N;";
					
					if (i == "licenses")
					{
						var packsUsed = false;
						
						if (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))
								{
									element5link += licensesPrices[j]["packs"][k]["element5passwords"][contractId][currency];
									packsUsed = true;
									break
								}
							}
						}
						
						if (!packsUsed)
						{
							element5link += licensesPrices[j]["element5passwords"][contractId][currency]
						}
					}
					else
					{
						if (i == "bundles")
						{
							element5link += bundlesPrices[j]["element5passwords"][contractId][currency]
						}
						else
						{
							if (i == "offers")
							{
								if (offersPrices[j]["price_percent"] > 0)
								{
									element5link += "offermd5" + contractId
								}
								else
								{
									element5link += offersPrices[j]["element5passwords"][currency]
								}
							}
						}
					}
				}
			}
			
			element5link += "&qpc=1";
			
			var procButton = $("#processButton");
				procButton.val($("#please_wait").html());
				procButton.attr("disabled", "disabled");
				
			if (offersData.length)
			{
				var postData = "";
				for (var i in offersData)
				{
					postData += "&offers[" + i + "]=" + offersData[i] + currency
				}
				
				ajax.post("/jcontroller/index.php", postData + "&ajaxmethod=getMd5", function (response)
				{
					eval("var hashes = " + response + ";");
				
					for (var i in hashes)
					{
						element5link = element5link.replace("offermd5" + i, hashes[i])
					}
					publicObject.redirectToElement5(element5link)
				})
			}
			else
			{
				this.redirectToElement5(element5link)
			}
		},	
		
        redirectToElement5: function($linkOParameters)
		{
            window.location = "https://secure.element5.com/esales/checkout.html?" + $linkOParameters
        },
        
        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 &&
            		_offerId == 4 ||
            		_offerId == 5 ||
            		_offerId == 7
            	)
            {
            	off4 = $("#off_4");
            	off5 = $("#off_5");
            	off7 = $("#off_7");
            		
            	var newCheckbox = $(document.createElement("input"));
                
                newCheckbox	.attr("id", "off_" + _offerId)
                			.attr("type", "checkbox")
                			.attr("class", "inpCheckbox");

                newCheckbox.bind("click", function()
                {
                	publicObject.calculateTotal(null, null, _offerId)
                });

                if(off4)
                {
               		off4.parent().append(newCheckbox);
                		
               		if( off4.is(":checked") )
               		{
               			newCheckbox.attr("checked", "checked")
               		}
               		off4.remove();
                	delete(selected.offers[4]);
                }	
                if(off5)
                {
                	off5.parent().append(newCheckbox);
                	if( off5.is(":checked") )
                	{
                		newCheckbox.attr("checked", "checked")
                	}
                	off5.remove();
                	delete(selected.offers[5]);
                }	
                if(off7)
                {
                	off7.parent().append(newCheckbox);
                	if( off7.is(":checked") )
                	{
                		newCheckbox.attr("checked", "checked")
                	}
                	off7.remove();
                	delete(selected.offers[7]);
                }	
                	
                var checked = $("#off_" + _offerId).is(":checked");
                	
                if (checked)
                {
                	selected.offers[_offerId] = true;
                }
                else
                {
                	delete(selected.offers[_offerId]);
                }
            }
            else
            {
            	  
                var checked = $("#off_" + _offerId).is(":checked");
            	
                if (checked)
                {
                	selected.offers[_offerId] = true;
                }
                else
                {
                	delete(selected.offers[_offerId]);
                }
            	
            }
          	this.checkCoupon()            
    //       	this.showTotal();
           	this.showOffersPrices();
        },
        
        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
            }
        },
		
		checkPlatform : function() {
				ajax.post("/jcontroller/index.php",
						"ajaxmethod=checkPlatform&productId="
					+ productId, {
							func : "oBuynow.checkPlatformSucc"
						})
		},
		checkPlatformSucc : function(value) {
			if (parseInt(value) == 0) {
				$("#note").show();
			} else {
				$("#note").hide();
			}
		},
		
		
		
		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
		}
	};

	$(document).ready( function()
	{
		

		var af5 = $("#af5");
		var af7 = $("#af7");
		
		 dele 	= $("#dele");
		 selecOp = $("#selecOp");
		
		dele.append(af5);
		dele.append(af7);	

		
		$("#processButton").val($("#process_my_order_now").html());
		$("#processButton").removeAttr("disabled");
		$(".er_contact").colorbox({iframe:true, innerWidth:'540px', innerHeight:'670px', speed:200,opacity:0.8});
		$(".contact").colorbox({iframe:true, innerWidth:'540px', innerHeight:'670px', speed:200,opacity:0.8});
		$("#bidFor").colorbox({iframe:true, innerWidth:'590px', innerHeight:'470px', speed:200,opacity:0.8});
		$("#upgradeNow option:first-child").attr('selected', 'selected');
		$("#upgradeNow").change( function(){productVer 	= $(this).attr('rel');selectedVal = $(this).val();if (parseInt(productVer) == parseInt(selectedVal)){$("#upgrade_link").colorbox({width:"50%", inline:true, href:"#upgrade_info_container p"});}else{$("#upgrade_link").unbind($.cbox_click).removeData($.colorbox).removeClass("cboxElement");}});var prodLinks = $(".prodLink > a");$.each(prodLinks, function(){this.href = this.href + '?ajax=true';$(this).colorbox({iframe:true, innerWidth:'80%', innerHeight:'70%', speed:200,opacity:0.8});});																																																																																																																																																																																																																																																																																																																																																																						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});});var licLinks = $(".hint");$.each(licLinks, function(){this.href = this.href + '?ajax=true';$(this).colorbox({iframe:true, innerWidth:'80%', innerHeight:'70%', speed:200,opacity:0.8});});
						
		$(".highl tr").bind( "mouseover", function()
		{
			$(this).children("td").css( "background-color", "#494949") });
			
			$(".highl tr").bind("mouseout",	function() 
			{
				$(this).children("td").css( "background-color", "#272727") });

				publicObject.showOffersPrices();
				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();
									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")
						});
						publicObject.checkPlatform();
					});
	return publicObject
}();
