FeedoStyleShop = {	
	init : function() {
	    FeedoStyleShop.updatePricesRecurring();
	   if ($('utmform')) {
			if (typeof __utmSetTrans != 'undefined'){
				Event.observe(window, 'load', __utmSetTrans, false);
			}
		}
	},
	toTitle : function(text) {
		var parts = text.split(' ');
		text = '';
		for (var i = 0; i < parts.length; i++) {
			text += parts[i].charAt(0).toUpperCase() + parts[i].substring(1) + ' ';
		}
		
		return text;
	},
	updatePrices : function() {
		var months = parseInt($F('months'));
		var productPrice = parseFloat($F('productPrice'));
		
		
		var amount = months * productPrice;
		var discount = 0;
		
		if ($('currentPlanPrice')) {
			var currentPlanPrice = parseFloat($F('currentPlanPrice'));
			var currentPlanMonths = parseInt($F('currentPlanMonths'));
			
			$('selectedMonths').innerHTML = months;
			$('upgradeAmount').innerHTML = amount.toFixed(2) + ' USD';
			//discount = currentPlanPrice * currentPlanMonths;
			$('discountAmount').innerHTML = discount.toFixed(2) + ' USD';
		} 
		
		if ($('additionalMonths')) {
			var text = months + ' month';
			if (months > 1) {
				text += 's';
			}
			$('additionalMonths').innerHTML = text;
			
			var date = new Date($F('expiryDate'));	
			$('prevExpiry').innerHTML = FeedoStyleShop.toTitle(date.toLocaleDateString());
			
			var year = date.getYear();
			var month = date.getMonth();
			if (year < 2000) {
				year += 1900;
			}			
			if (month + months >= 12) {
				year++;
				month += months % 11;
			} else {
				month += months;
			}
			
			date.setMonth(month);
			date.setYear(year);
			
			$('newExpiry').innerHTML = FeedoStyleShop.toTitle(date.toLocaleDateString());
		}
	
		$('totalAmount').innerHTML = (amount - discount).toFixed(2) + ' USD';
		if ($('totalAmount2')) {
			$('totalAmount2').innerHTML = (amount - discount).toFixed(2) + ' USD';
		}
	},
	days_between : function (date1, date2) {

        // The number of milliseconds in one day
        var ONE_DAY = 1000 * 60 * 60 * 24

        // Convert both dates to milliseconds
        var date1_ms = date1.getTime()
        var date2_ms = date2.getTime()

        // Calculate the difference in milliseconds
        var difference_ms = Math.abs(date1_ms - date2_ms)
        
        // Convert back to days and return
        return Math.round(difference_ms/ONE_DAY)

    },
       updatePricesRecurring : function() {
	    
	    if($('totalAmount'))
	    {
	       var m_names = new Array("January", "February", "March", 
                                    "April", "May", "June", "July", "August", "September", 
                                    "October", "November", "December");

	        var months = 1; //payment frequency set at 1 month
		    var productPrice = parseFloat($F('productPrice'));
		    var amount = 0;
		    var currentPlanPrice = 0;
		    var currentMonths = 1;
		    
		    if($('currentPlanPrice'))
		    {
		        currentPlanPrice = $F('currentPlanPrice');
		        currentMonths = $F('currentMonths');
		    }
		    
		    
		    var productCode = $F('productCode');
    		var transType = '';
    		
    		
    		switch(productCode.substring(productCode.length - 3))
    		{
    		    case 'PUR':
    		        transType = 'purchase';
    		    break;
    		    case 'UPG':
    		        transType = 'upgrade';
    		    break;
    		    case 'DNG':
    		        transType = 'downgrade';
    		    break;
    		}
    		
    		if(transType=='purchase')
    		{
        		if($F('currentPlanName') == 'Community')
        		{
        		    $('upgradeSummary').innerHTML = '';
		            $('upgradeSummaryContainer').style.display='none';
        		}
    		    amount =  months * productPrice;
    		}
    		else if(transType == 'upgrade')
    		{
    		    if($F('currentPlanName') == 'Community')
    		    {
    		        amount =  months * productPrice;
		            $('upgradeSummary').innerHTML = '';
		            $('upgradeSummaryContainer').style.display='none';
    		    }
    		    else
    		    {
    		          var expiry = new Date($F('expiryDate'));
    		    
		              var days = FeedoStyleShop.days_between(expiry,new Date());
		             
		              var currentpriceperday = currentPlanPrice/31;
		              
		              var amount = ((productPrice - currentPlanPrice)/31) * days;
		              
		              if(amount < 0)
		                amount = 0;
		              
		              var currentDate = expiry.getDate() + " " + m_names[expiry.getMonth()] + " " + expiry.getFullYear();

		                var summary = 'Next payment date: ' + currentDate + '<br/><br/>New plan rate: ' + productPrice.toFixed(2) + ' USD per month';
		                summary+= '<br/><br/><b>Upgrade Total:</b> ' + amount.toFixed(2) + ' USD';
		                summary+= '<br/><br/><b>Regular payment : </b> ' + (productPrice*months).toFixed(2) + ' USD per month';
		                $('upgradeSummary').innerHTML = summary;
    		    }
    		}
    		else if(transType == 'downgrade')
    		{
    		   $('purchaseBtn').value = 'Continue';
    		   $('purchaseBtn').onclick=FeedoStyleShop.downGrade;
    		    amount =  0;
		    }
		    
        $('totalAmount').innerHTML = amount.toFixed(2) + ' USD';
    		 
	  }else if($('action'))
	  {
	    if($F('action')=='cancel')
	    {
	         $('purchaseBtn').value = 'Continue';
    		 $('purchaseBtn').onclick=FeedoStyleShop.cancelAccount;
        }
	  }
	},
	cancelAccount : function()
	{
	   var completed = function(response)
	     {
	            var result = eval('(' + response.responseText + ')');
    	        
			    if (result.isSuccessful) {
    		            window.location.href = result.page;
		            }
		            else
		            {
    		            FeedoStyleWeb.showError('An unexpected error occurred. Please try again.'); 
			            $('purchaseBtn').disabled = false;
			            $('purchaseBtn').value = 'Continue';	
		    	        $('processing').style.display = 'none';
		            }
	     };
	 
	 var loadError = function() {
			FeedoStyleWeb.showError('An unexpected error occurred. Please try again.');
		    $('purchaseBtn').disabled = false;
		    $('purchaseBtn').value = 'Continue';
		    $('processing').style.display = 'none';
		};
	 
	var email = $F('email');
	 
	 Effect.Appear('processing');
		var url = window.location.href;
	    var pars = 'cback=cancel&email=' + email  + '&seed=' + Math.floor(Math.random()*999999);
	    
	    $('purchaseBtn').disabled = true;
	    $('purchaseBtn').value = 'Processing...';  
	    
	 var ajax = new Ajax.Request(url, { 
            method: 'post', 
            parameters: pars,
            onFailure: loadError,
            onSuccess: completed }); 
	
	},
	downGrade : function()
	{
	    var completed = function(response)
	     {
	            var result = eval('(' + response.responseText + ')');
    	        
			    if (result.isSuccessful) {
    		            window.location.href = result.page;
		            }
		            else
		            {
    		            FeedoStyleWeb.showError('An unexpected error occurred. Please try again.'); 
			            $('purchaseBtn').disabled = false;
			            $('purchaseBtn').value = 'Continue';	
		    	        $('processing').style.display = 'none';
		            }
	     };
	 
	 var loadError = function() {
			FeedoStyleWeb.showError('An unexpected error occurred. Please try again.');
		    $('purchaseBtn').disabled = false;
		    $('purchaseBtn').value = 'Continue';
		    $('processing').style.display = 'none';
		};
	 
	 var productPrice = $F('productPrice');
	 var newPlan = $F('newProduct');
	 var email = $F('email');
	 var code = $F('productCode').replace('[MONTH]', '1');
	 
	 Effect.Appear('processing');
		var url = window.location.href;
	    var pars = 'cback=downgrade&newPlan=' + newPlan + '&code=' + code + '&email=' + email + '&productPrice=' + productPrice + '&seed=' + Math.floor(Math.random()*999999);
	    
	    $('purchaseBtn').disabled = true;
	    $('purchaseBtn').value = 'Processing...';  
	    
	 var ajax = new Ajax.Request(url, { 
            method: 'post', 
            parameters: pars,
            onFailure: loadError,
            onSuccess: completed });
	},
	goShop : function() {
		window.location.href = '/shop/default.aspx';
	},
	purchase : function() {
		var validatePurchase = function(response) {
			var result = eval('(' + response.responseText + ')');
			if (result.isSuccessful) {
		        if (typeof urchinTracker != 'undefined'){
			        urchinTracker('/goals/purchase');
		        }
				window.location.href = result.page;
			} else {
				FeedoStyleWeb.showError('An unexpected error occurred. Please try again.'); 
			    $('purchaseBtn').disabled = false;
			    $('purchaseBtn').value = 'Purchase';	
		    	$('processing').style.display = 'none';
			} 
		};
		var loadError = function() {
			FeedoStyleWeb.showError('An unexpected error occurred. Please try again.');
		    $('purchaseBtn').disabled = false;
		    $('purchaseBtn').value = 'Purchase';
		    $('processing').style.display = 'none';
		};

		var amount = parseFloat($('totalAmount').innerHTML);
		
        var firstName = $F('firstName');
        var lastName = $F('lastName');
        var email = $F('email');
        var months = 1;
      
        if(!$('months'))
        {
            months = $F('currentMonths');
        }
        else
        {
            months = parseInt($F('months'));
        }
        
        var code = $F('productCode').replace('[MONTH]', months);
        
		Effect.Appear('processing');
		var url = window.location.href;
	    var pars = 'cback=purchase&amount=' + amount + '&code=' + code + '&months=' + 1 + '&firstname=' + firstName + '&lastName=' + lastName + '&email=' + email + '&seed=' + Math.floor(Math.random()*999999);
	    $('purchaseBtn').disabled = true;
	    $('purchaseBtn').value = 'Processing...';  	    
   
        var ajax = new Ajax.Request(url, { 
            method: 'post', 
            parameters: pars,
            onFailure: loadError,
            onSuccess: validatePurchase });
	}
};
Event.observe(window, 'load', FeedoStyleShop.init, false);
