var currency = "";
var FADE_TIME = 200;
var COUPON_FLAG = false;
var activeTab = '';
$(document).ready(function() {
	currency = $("#product_currency").val();
	
	//MouseOver Event
	$(".carousel-2-box li").mouseenter(function() {
		activeTab = "#"+$(this).find("a").attr("title"); //Find the rel attribute value to identify the active tab + content		
		if ($(activeTab+"-desc").css('opacity')!='1'){
			$(".store-desc-content").css('z-index','5').stop().animate({'opacity':'0'},FADE_TIME); //Hide all tab content
			$(activeTab+"-desc").css('z-index','10').stop().animate({'opacity':'1'},FADE_TIME); //Fade in the active content
	
		}
		return false;
	});
	
	//MouseOut Event
	$(".carousel-2-box ul").mouseleave(function() {
		activeTab = "#"+$(".carousel-2-box li.active").find("a").attr("title"); //Find the rel attribute value to identify the active tab + content
		$(".store-desc-content").stop().animate({'opacity':'0'},FADE_TIME); //Hide all tab content
		$(activeTab+"-desc").stop().animate({'opacity':'1'},FADE_TIME); //Fade in the active content
		return false;
	});	
	
	// coupon submit on enter..
	$('.couponcode').bind('keypress', function(e) {
        if(e.keyCode==13){
              renew_cupon();
              
        }
	});
	
	$("#email").focus(function(){
			$(this).removeClass('input_field_error');
			if($(this).attr('value') == "Enter your e-mail address") $(this).attr('value','');
			//changeButton('linz');
		}).blur(function(){
			if($(this).attr('value') == "") $(this).attr('value','Enter your e-mail address');
		});
	
	$("#field_focus").css({'opacity':'0','display':'block'});
});
 

    function get_price(price, stype, discount){    
    	if(stype == "procents"){		
			price = price/100*(100-discount);
			price = price.toFixed(2); 
		}else{
			price = price - discount;
			price = price.toFixed(2);		
		}
		return price;	    
    }
 
    function recalc_price(type, num, cupon_code){
    	currency = $("#product_currency").val();
        if(cupon_code == 'TEN/10/TEN' || cupon_code == 'ten/10/ten'){
    		price = get_price($('#price_cmmlifetime').val(), type, num);
    		$('#'+ 'cmmlifetime'+ "_price").html(currency + price); 
    		url = $('#'+ 'cmmlifetime' + "_link").attr("href");
    		$('#'+ 'cmmlifetime' + "_link").attr("href", url+"&coupon="+cupon_code);
    		
    	}else if(cupon_code == 'ENMH5' || cupon_code == 'enmh5'){
    		price = get_price($('#price_ensoul').val(), type, num);
    		$('#'+ 'ensoul'+ "_price").html(currency + price); 
    		url = $('#'+ 'ensoul' + "_link").attr("href");
    		$('#'+ 'ensoul' + "_link").attr("href", url+"&coupon="+cupon_code);
    		
    	}else{
    
		$(".productsListArr").each(function(index) {
			var url = "";
    		price = get_price($('#price_'+ $(this).val()).val(), type, num);
    		$('#'+ $(this).val()+ "_price").html(currency + price); 
    		old_url = $('#'+ $(this).val()+ "_link").attr("href");
			url_array = old_url.split('&');
			for(k = 0; k < url_array.length; k++){
				url_param = url_array[k].split('=');
				if (url_param[0]!='coupon')	{
					url += url_array[k];
					if (k+1 < url_array.length) url += '&';
				} else {
					COUPON_FLAG = true;
				}
			}
			if (!COUPON_FLAG) url += '&';
    		$('#'+ $(this).val()+ "_link").attr("href", url+"coupon="+cupon_code);
  		});	
  		}
	} 
    
    function set_skidka(type, number, cupon_code){
     if(cupon_code == 'TEN/10/TEN' || cupon_code == 'ten/10/ten'){
    	$(".coupon_cutted").hide();
  		$(".coupon_cutted_ok").fadeIn();  		
  	  	$("#cmmlifetime_oldprice").fadeIn();
		$("#cmmlifetime_oldprice").prepend('<div id="cline2" class="cross-line" style="display: block; top:14px;"></div>');	
		
	  }else if(cupon_code == 'ENMH5' || cupon_code == 'enmh5'){
	  	
	  	$(".coupon_cutted").hide();
	  	$(".coupon_cutted_ok").fadeIn();  		
  	  	$("#ensoul_oldprice").fadeIn();
	//	$("#ensoul_oldprice").prepend('<div id="cline2" class="cross-line" style="display: block; top:14px;"></div>');
		$(".10_cross-line").fadeIn();
	  }else{
		$(".coupon_cutted").hide();
  		$(".coupon_cutted_ok").fadeIn();  		
  		$(".oldprice").fadeIn();
		$(".cross-line").fadeIn(); 
	  }
    }
    
	function removeWrongBG(cval){
		$(".couponcode").css('background', "url(/images/bg_code_input_all.png) 0 0 no-repeat");
		$(".couponcode").val(cval);
		$("#cupon").focus();
	}

	
	function couponcheck(cpn){
		$('#field_focus').animate({'opacity':'0'},300);
		if (cpn.value=='' || cpn.value==cpn.defaultValue) {
			cpn.value=cpn.defaultValue;
			cpn.style.color='#837F7B';
		}else{
			cpn.style.color='#334860';
		}
	}
	
	function couponedit(cpn){
		$('#field_focus').animate({'opacity':'1'},300);
		if (cpn.value=='' || cpn.value==cpn.defaultValue) {
			cpn.value='';
			cpn.style.color='#334860';
		}
	}
	
		
	function renew_cupon(){	
		lang = $("#coupon_site_lang").html();
		nullUpdatedStats('coupon');
		cupon_code = document.getElementById('cupon').value;
		if(cupon_code){
			JsHttpRequest.query(
            	'xml.GET /coupons_backend', // backend
            	{
            		'backendtype': 'check_coupons',
                		'cupon_code': cupon_code,
                		'lang': lang
            	},
            	// Function is called when an answer arrives. 
            	function(result, errors) {
                if (result["resultxt"]=='submited') {     	        				   
					if(result["discount"]!=0){ 

						$(".productsListArr").each(function(index) {
							if ( $('#'+$(this).val()+'_div_link').html() != null) {
								$('#'+$(this).val()+'_link').attr('href', $('#'+$(this).val()+'_div_link').html());
							}
						});

						if (sessionStorage != null) {
							sessionStorage.removeItem('email');
							sessionStorage.coupon = cupon_code;
						}
						set_skidka(result["type"], result["discount"], cupon_code);
						recalc_price(result["type"], result["discount"], cupon_code);
						recalculateSave('set');
						$(".coupon_cutted_ok").html("<table><tr height='105'><td valign='middle'><div class='crestxt'>"+result["text"]+"</div></td></tr></table>");
					}else{

						$("#cupon").blur();
						// set error BG
						$(".couponcode").css('background', "url(/images/bg_code_input_all.png) 0 -41px no-repeat");
						cval = $(".couponcode").val();	
						$(".couponcode").val('');					
						setTimeout("removeWrongBG('"+cval+"')", 800);		
					} 		
                }
            },
            false  // do not disable caching
    	    	);
			}
		}
	
	

	function discount_renew_coupon(coupon){	
		lang = $("#coupon_site_lang").html();
		nullUpdatedStats('coupon');

		if(coupon){
			JsHttpRequest.query(
		            	'xml.GET /coupons_backend', // backend
				{
					'backendtype': 'check_coupons',
					'cupon_code': coupon,
					'lang': lang
				},
				// Function is called when an answer arrives. 
				function(result, errors) {
					if (result["resultxt"]=='submited') {     	        				   
						if(result["discount"]!=0){ 
						
							if ($('.top_offer').height() != 0 && $('.top_offer').height() != null) {
								$('html,body').stop().animate({scrollTop: 375}, FADE_TIME*2, 'easeOutQuart')
							} else {
								$('html,body').stop().animate({scrollTop: 305}, FADE_TIME*2, 'easeOutQuart')
							}
							
							$(".oldprice").fadeIn();
							$(".cross-line").fadeIn(); 

							$(".productsListArr").each(function(index) {
								var url = "";
								price = get_price($('#price_'+ $(this).val()).val(), result["type"], result["discount"]);
								$('#'+ $(this).val()+ "_price").html(currency + price); 
							    	
							    	url = $('#'+ $(this).val()+ "_link").attr("href");
							
							
							
								$('.' + $(this).val() + '_cross-line').show();
								$('.' + $(this).val() + '_oldprice').show();
							
								oldprice = $('#' + $(this).val() + '_oldprice').html();

								if (oldprice != null){
									href = $('#' + $(this).val() + '_buy > a').attr('href');
									form = '';
									form += '<form method="post" action="' + url + '" id="' + $(this).val() + '_form" style="display:none;">';
									form += '<input type="hidden" name="coupon" value="' + coupon + '" />';
									form += '</form>';
									form += '<div style="display:none;" class="hidden_link" id="' + $(this).val() + '_div_link">' + url + '</div>';
									$('#' + $(this).val() + '_link').parent().prepend(form);
									$('#' + $(this).val() + '_link').attr('href', 'javascript: $("#' + $(this).val() + '_form").submit()');
									$('#' + $(this).val() + '_link').removeAttr('onclick');
								}
							
							});
							recalculateSave('set');
						}		
					}
				},
				false  // do not disable caching
			);
		}
	}
	
	




var TIME = 400;
var post_success = false;
var post_result = "";

	function isValidEmail(){
		var email = $("#email").attr('value');
		email = email.replace(/^\s+|\s+$/g, '');
		mvalid =(/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
		return mvalid;
	}


	function licenseUpgrade(){
		lang = $("#coupon_site_lang").html();
		$("#email").blur();
		nullUpdatedStats('lu');
		if($("#input_field_container").width() == '0'){
			showInputLU();
		} else if ($("#email").attr('value') != '' && $("#email").attr('value') != 'Enter your e-mail address'){
			if(!isValidEmail()){
				showEmailError('notvalid');
				changeButton('check_error');
			} else {
				changeButton('checking');
				$.get("/upgrade_license",
					{
						'email': $("#email").attr('value'),
						'lang': lang
					},
					function(data){
						new_data = data.split('|');
						if(new_data[0] != 'ERROR' && data!=''){
							if (sessionStorage != null) {
								sessionStorage.email = $("#email").attr('value');
								sessionStorage.removeItem('coupon');
							}
							upgrade(data);
							recalculateSave('set');
							post_result = data;
							post_success = true;
							showEmailError('success');
							changeButton('check_ok');
						} else {
							post_success = false;
							showEmailError('error');
							changeButton('check_error');
						}
					});
			}
		} else {
			showEmailError('notvalid');
		}
	}

	function showInputLU(){
		$('#email').attr('value','Enter your e-mail address');
		$("#input_field_container").stop().animate({'width': ($("#email").width() + 22) + 'px'},TIME);
		showEmailError('verify');
		$("#iButton sub").addClass("square");
		changeButton('check');
	}

	function changeButton(object){
		switch (object){
			case 'check':
				$("#button_icon").removeClass().addClass('iButton_Linz');
				$("#button_text").html('Check&nbsp;');
				break;
			case 'check_ok':
				$("#iButton sub").removeClass("square");
				$("#button_icon").removeClass().addClass('iButton_Check');
				$("#button_text").html('Reset&nbsp;');
				break;
			case 'checking':
				$("#button_icon").removeClass().addClass('iButton_Loader');
				$("#button_text").html('Checking');
				break;
			case 'check_error':
				$("#button_icon").removeClass().addClass('iButton_Reset');
				$("#button_text").html('Recheck');
				break;
			default:
				showEmailError();
				$("#button_icon").removeClass().addClass('iButton_Arrow');
				$("#iButton sub").removeClass("square");
				$("#button_text").html('Upgrade');
				break;
		}
	}

	function upgrade(data){
		products = data.split('|');
		for(i = 0; i < products.length; i++ ){
			prod = products[i].split(',');
			id = prod[0];
			url = prod[1];
			coupon = prod[2];
			discount = prod[3];
			type = prod[4];
			$('.' + id + '_cross-line').show();
			$('.' + id + '_oldprice').show();
			oldprice = $('.' + id + '_oldprice').html();
			if (oldprice != null){
				recalculatePrice(oldprice, type, discount, id);
				href = $('#' + id + '_buy > a').attr('href');
				form = '';
				form += '<form method="post" action="' + url + $("#upgrade_license_params").html() + '" id="' + id + '_form" style="display:none;">';
				form += '<input type="hidden" name="coupon" value="' + coupon + '" />';
				form += '</form>';
				form += '<div style="display:none;" class="hidden_link" id="' + id + '_div_link">' + href + '</div>';
				$('#' + id + '_buy').prepend(form);
				$('#' + id + '_buy > a').attr('href', 'javascript: $("#' + id + '_form").submit()');
				$('#' + id + '_buy > a').removeAttr('onclick');
			}
		}
	}
	
	function nullUpdatedStats(act){
		if(act == 'coupon'){
			$("#input_field_container").stop().animate({'width':'0px'},TIME);
			changeButton();
			window.setTimeout("$('#email').attr('value','Enter your e-mail address')",TIME);
			
		}
		if (act == "lu"){
			$(".productsListArr").each(function(index) {
				if ( $('#'+$(this).val()+'_div_link').html() != null) {
					$('#'+$(this).val()+'_link').attr('href', $('#'+$(this).val()+'_div_link').html());
				}
			});

			$("#cupon").attr('value','');
			$(".coupon_cutted").show();
			$(".coupon_cutted_ok").hide();  		
			$(".oldprice").hide();
			$(".cross-line").hide();
			$(".productsListArr").each(function(index) {
				new_url = "";
				$('#'+ $(this).val()+ "_price").text(currency + '' + $('#price_'+ $(this).val()).val()); 
				url = $('#'+ $(this).val()+ "_link").attr("href");
				url_vars = url.split('&'); // array orr url variables
				for (i = 0; i < url_vars.length; i++){
					u = url_vars[i].split('=');
					if (u[0] != 'coupon'){
						if (i != 0) new_url += "&";
						new_url += url_vars[i];
					}
				}
				$('#'+ $(this).val()+ "_link").attr("href", new_url);
			});	

			recalculateSave();
		}
		if ($(".hidden_link").length > 0){
			products = post_result.split('|');
			for(i = 0; i < products.length; i++ ){
				prod = products[i].split(',');
				id = prod[0];
				url = prod[1];
				coupon = prod[2];
				discount = prod[3];
				type = prod[4];
				$('.' + id + '_cross-line').hide();
				$('.' + id + '_oldprice').hide();
				oldprice = $('.' + id + '_oldprice').html();
				$('.' + id + '_price').html(oldprice);
				tmp_onclick = $('#' + id + '_div_onclick').text();
				tmp_href = $('#' + id + '_div_link').text();
				tmp_class = $('#' + id + '_buy > a').attr('class');
				tmp_id = $('#' + id + '_buy > a').attr('id');
				new_a = '<a href="' + tmp_href + '" class="' + tmp_class + '" id="' + tmp_id + '" onclick="' + tmp_onclick + '">&nbsp;&nbsp;&nbsp;</a>';
				$('#' + id + '_buy > a').remove();
				$('#' + id + '_buy').html(new_a);
				$('#' + id + '_form').remove();
				$('#' + id + '_div_link').remove();
			}
		}
		
	}
	
    function recalculatePrice(oldprice, type, discount, id){
		price = "";
		for(j = 1; j < oldprice.length; j++){
			price += oldprice.charAt(j);
		}
    	if(type == "procents"){		
			price = price/100*(100-discount);
			price = price.toFixed(2); 
		}else{
			price = price - discount;
			price = price.toFixed(2);		
		}
		price = currency + price;
		$('.' + id + '_price').html(price);
    }
	
	
	function showEmailError(id){
		switch (id){
			case 'verify':
				$(".step").hide();
				$("#step_verify").show();
				break;
			case 'success':
				$("#input_field_container").stop().animate({'width':'0px'},TIME);
				$(".step").hide();
				$("#step_success").show();
				break;
			case 'error':
				$(".input_field").addClass('input_field_error');
				$(".step").hide();
				$("#step_error").show();
				break;
			case 'notvalid':
				$(".input_field").addClass('input_field_error');
				$(".step").hide();
				$("#step_notvalid").show();
				break;
			default:
				$(".step").hide();
				$("#step_1").show();
				break;
		}
	}
	
	function recalculateSave(act){
		save = $(".saved");
		if (act != 'set'){
			for (n = 0; n < save.length; n++){
				full_id = save[n].id;
				$("#" + full_id).html($("#" + full_id + '_base').html());
			}
		} else {
			for (n = 0; n < save.length; n++){
				full_id = save[n].id;
				id = '';
				for (k = 6; k < full_id.length; k++){
					id = id + full_id.charAt(k);
				}
				this_price = $("." + id + "_price").html();
				this_price = this_price.slice(1,this_price.length);

				this_oldprice = $("." + id + "_oldprice").html();
				this_oldprice = this_oldprice.slice(1,this_oldprice.length);				
				this_saved = $("#saved_" + id + "_base").html();
				
				minus = this_oldprice - this_price;
				
				$("#saved_" + id).html((((minus.toFixed(2)*2)+(this_saved)*2)/2).toFixed(2));
			}
		}
	}




$.extend($.easing, {
	easeOutQuart: function(x, t, b, c, d) {
		return -c * ((t = t / d - 1) * t * t * t - 1) + b;
	}
});

