$(function(){					
	$(window).resize(function(){
	resizePopup();
	});	
	setGiftCoupon();
	setGiftCouponPayAmount();
	//checkPaymentNeeded();
    if($.trim($('#giftFromName').val())!=''){
        $('#from-name').html($.trim($('#giftFromName').val()));
    }
    if($.trim($('#couponTo').val())!=''){
        $('#to-name').html($('#couponTo').val());
    }
    if($.trim($('#couponMessage').val())!=''){
        $('#gift-message').html($.trim($('#couponMessage').val()));
    }
    var sendMode =($('input:radio[name=sendMode]:checked').val());
    showHide(sendMode);
    $('input:radio[name=sendMode]').click(function(){
        var sendMode =($('input:radio[name=sendMode]:checked').val());
        showHide(sendMode);
    })
	$(document).on('click','.giftCardStyle',function(){
		$("#giftEmailTemplateDiv").val($(this).attr('id'));	  
		$('.giftCardStyle').removeClass("active");
		$(this).addClass("active");
		var theme             =$(this).children().attr('id');
		var giftEmailTemplateID=$(this).children().attr('rel');
		$('#giftEmailTemplateID').val(giftEmailTemplateID);
		$('.gift-pane').removeClass().addClass('gift-pane').addClass(theme);
    })
    $('#giftFromName').keyup(function(){
        $('#from-name').html($('#giftFromName').val());
    })

    $('#giftFromName').blur(function(){
        $('#from-name').html($('#giftFromName').val());
    })
    $('#couponTo').keyup(function(){
        $('#to-name').html($('#couponTo').val());
    })
    $('#couponTo').blur(function(){
        $('#to-name').html($('#couponTo').val());
    })
	$(document).on("click",'.giftPreview',function(){
		$("#giftPreview-container").html('');
		$('#giftPreviewLoader').css('padding-top', (($('.giftPreview-popup').innerHeight())/2)-15 + 'px');  
		$("#giftPreviewLoader").show();					
		$(".giftPreview-pop-section").show();				
		resizePopup(); 
		var formData = $("#formProductPayment").serialize();
		$.ajax({
				type: "POST",
				url: GLOBAL_BASE_PATH + "/giftcoupon/giftPreviewAjax/",
				data: formData,
				success: function (msg) 
				{          		
					$("#giftPreviewLoader").hide();
					$("#giftPreview-container").html(msg);							  
				}
			});
    });	
	$(document).on("click",'.giftPreview-close-img',function(){
	$(".giftPreview-popup").hide();	
	$(".giftPreview-pop-section").hide();					 
    });	
    $('#couponAmount').blur(function(){
       var html =   $('#gift-amount').html();
       var val  =   $('#couponAmount').val();
       if(val=='' || val==0) {
       var val  =   $('#couponAmount').val(5);
	   }else{	 
	   if(!checkLetters(val)){
         // $('#gift-amount').html(numberReplace(html, val,initAmount));
       }
	   }
	   setGiftCouponPayAmount();
        checkPaymentNeeded();
        //$('#gift-amount').html($('#couponAmount').val());
    })

	$(document).on("keydown","#couponAmount",function(event) {
		  if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) 
		  {
		  } 
		  else 
		  {
			   if (event.keyCode < 95) 
			   {
					if (event.keyCode < 48 || event.keyCode > 57 ) 
					{
					 event.preventDefault();
					}
			   } 
			   else 
			   {
					if (event.keyCode < 96 || event.keyCode > 105 ) 
					{
					 event.preventDefault();
					}
		   	   }
			   if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) 
			   {
                	event.preventDefault(); 
               }  
		  }
	});
})

function numberReplace(s,d,i) {
   if(/\d/.test(s)){
       return s.replace (/\.?\d[\d.,]*/, d);
   }
   else{
       return i.replace (/\.?\d[\d.,]*/, d);
   }
}
function checkLetters(str){
     var reg = /[^0-9.]/;
     return reg.test(str)
}
function validate(item){
	var StrippedString =item.val().replace(/(<([^>]+)>)/ig,"");
	if(item.val()!=StrippedString)
	{
		jAlert(lblHtmltags);	
	}
	item.val(StrippedString);
	return true;
}

function showHide(sendMode){
    if(sendMode == 'Email') {
        $('#to-email-li').show();
    }
    else{
        $('#to-email-li').hide();
    }
	setEmailHidden(sendMode);
}

function setEmailHidden(sendMode)
{
	var couponEmailTo=$("#couponEmailTo").val();
	var couponEmailToHidden=$("#couponEmailToHidden").val();	
	if(sendMode == 'Email') 
	{
		if(couponEmailToHidden!='')
		$("#couponEmailTo").val(couponEmailToHidden);		
	}
	else
	{		
		$("#couponEmailToHidden").val(couponEmailTo);
		$("#couponEmailTo").val('');		
	}
}

function setGiftCoupon()
{
	var giftEmailTemplateDiv=$("#giftEmailTemplateDiv").val();	
	$('.giftCardStyle').removeClass("active");
	$("#"+giftEmailTemplateDiv).addClass("active");
	var theme             =$("#"+giftEmailTemplateDiv).children().attr('id');
	var giftEmailTemplateID=$("#"+giftEmailTemplateDiv).children().attr('rel');
	$('#giftEmailTemplateID').val(giftEmailTemplateID);
	$('.gift-pane').removeClass().addClass('gift-pane').addClass(theme);	
}

function resizePopup()
{
 if ($('.giftPreview-pop-section').is(':visible')) {
 $('.giftPreview-popup').css({
    position:'fixed',
	display:'block',
	  left: ($(window).width() - $('.giftPreview-popup').outerWidth())/2,
	 right: ($(window).width() - $('.giftPreview-popup').outerWidth())/2,
    top: ($(window).height() - $('.giftPreview-popup').outerHeight())/2
  });
 }
}

var uncheckedkeycodes=/(8)|(13)|(16)|(17)|(18)/  //keycodes that are not checked, even when limit has been reached.

function setformfieldsize($fields, optsize, optoutputdiv){
	var $=jQuery
	$fields.each(function(i){
		var $field=$(this)
		$field.data('maxsize', optsize || parseInt($field.attr('data-maxsize'))) //max character limit
		var statusdivid=optoutputdiv || $field.attr('data-output') //id of DIV to output status
		$field.data('$statusdiv', $('#'+statusdivid).length==1? $('#'+statusdivid) : null)
		$field.unbind('keypress.restrict').bind('keypress.restrict', function(e){
			setformfieldsize.restrict($field, e)
		})
		$field.unbind('keyup.show').bind('keyup.show', function(e){
			setformfieldsize.showlimit($field)
		})
		setformfieldsize.showlimit($field) //show status to start
	})
}
setformfieldsize.restrict=function($field, e){
	var keyunicode=e.charCode || e.keyCode
	if (!uncheckedkeycodes.test(keyunicode) && validate($field)){
		if ($field.val().length >= $field.data('maxsize')){ //if characters entered exceed allowed
			if (e.preventDefault)
				e.preventDefault()
			return false
		}
	}
}
setformfieldsize.showlimit=function($field){
	if ($field.val().length > $field.data('maxsize')){
		var trimmedtext=$field.val().substring(0, $field.data('maxsize'))
		$field.val(trimmedtext)
	}
	if ($field.data('$statusdiv')){
		$field.data('$statusdiv').html($field.data('maxsize') - $field.val().length)		
	}
}
$(document).ready(function($){ 
	setformfieldsize(jQuery('#couponMessage'), 130, 'charcount');
	$(document).on("blur",'#couponMessage',function(){
     	validate($(this));
		if($(this).val() !=''){
	 		$(this).val($(this).val().slice(0, 130));
		} 
    });
	
	$(document).on("blur",'#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone',function(){
		validate($(this));
    });
	
	$('#billingFirstName,#billingLastName,#billingAddress,#billingAddress1,#billingProvince,#billingCity,#billingZip,#billingPhone').each(function(){
		validate($(this));
	});
	
	
})
function setGiftCouponPayAmount()
{
	if($("#orderType").val()=='Coupon')
	{
		var availableAmt = $("#availableAmt").val();	
		var couponAmount = parseInt($("#couponAmount").val());	
		var checkAmount =  couponAmount-availableAmt;
		var amountToBePaid = 0;
		if(checkAmount>0)
		{
			var decimalPlaces = $("#currencyDecimalPlaces").val();	
			if(checkAmount % 1 != 0 && decimalPlaces!='')
			checkAmount = checkAmount.toFixed(decimalPlaces);
			amountToBePaid = checkAmount;	
		}		
		$("#ajaxAmountToBePaid").html(amountToBePaid);
	}
}
