/*************************************************************************
 * @author Jaiky Manuja
 * @date 24/09/2015
 * @description :  This file is for:  
	- Redirecting a user to BigCommerce. 
	- Confirm user details before redirecting to shop
	- Display 'Member Login' OR 'My Membership' based on logged in and guest user.	
	
 *************************************************************************/
var storeURL = 'https://shop.diabetesvic.org.au/';
var ShopDetails = {};
var userDetailsJson = {};
var redirect = {
    data: {
        url: storeURL+'login.php?action=check_login',
        redirect: storeURL,
        login: '',
        pass: ''
    },
    form: function() {

    	var userAgent = window.navigator.userAgent;
        var checkIE = userAgent.indexOf("MSIE ");
        if (checkIE > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
        	window.location = storeURL;
        } else {
        	var f = '<form method="post" id="bc" action="' + redirect.data.url + '">' + '<input type="text" name="login_email" value="' + redirect.data.login + '"/>' + '<input type="password" name="login_pass" value="' + redirect.data.pass + '" />' + '<input type="submit" value="Login" />' + '</form>';
	        $('iframe#ifr').contents().find('html > body').html(f);
	        $('#ifr').contents().find('form#bc').submit();
        }
    },
    events: function() {
        $(document).on("click", "#modalBox", function(e) {
            e.preventDefault();
            if (redirect.data.login != '' && redirect.data.pass != '') {
                $('#basicModal').modal('show');
            }
        });
        $(document).on("click", "#send", function(e) {	
        	if($(this).hasClass('verifyLogin')){
        		return false;
        	}
        	var originalText = $("#send").text()		 
			var cardType = $('li.container #cardType:visible option:selected').text();
			var cardTypeVal = $('li.container #cardType:visible option:selected').val();			
			var userDetailsObject = {
                "NDSSNumber": $("li.container #NDSSNumber").val(),
				"accountId": userDetailsJson.AccountId,
                "action": "updateCard",
				"ConcessionCardType": cardType,
				"ConcessionCardNumber": (cardTypeVal==0)? '' : $("li.container #cardNumber").val(),
				"cardExpDate": (cardTypeVal==0)? '' : $("li.container #cardExpDate").val()                  
            };			
			if($("li.container #shopForm").valid()){
				$("#send").text('Verifying...').addClass("verifyLogin");  				
				$("li.container #errorshop").html('');
				$.orchestracmsRestProxy.doAjaxServiceRequest('DV_Shop_Service', userDetailsObject, function(testStatus, json, xhr) {
					if (json.success) {
						$("div#showLoader").show();
						$("span#loading-content").html('Now logging you into the shop to personalise your experience.');				
						redirect.sendToBigCommerce();
					}else{
						$("#send").text(originalText).removeClass("verifyLogin");
					    //$("div#showLoader").hide();							    
					    $("li.container #errorshop").html(''+json.syncStatus);											    
					}
				});
			}
        });
    },
    sendToBigCommerce: function() {
		$("div#showLoader").show();
        redirect.form();
        setTimeout(function() {
            window.location = redirect.data.redirect;
        }, 5000);
    },
	/*Check*/
    checkUserStatus: function() {		
        if (redirect.data.login != '' && redirect.data.pass != '') {			
            $("ul#nav-mobile > li:eq(1) > ul.dropdown-menu > li").hide();
            $("ul#nav-mobile > li:eq(1) > ul.dropdown-menu").append('<li class="container">' + $('#basicModal .modal-body').html() + ' ' + $('#basicModal .modal-footer').html() + '</li>');			
			redirect.setValuesForSop();				
        }
    },
	setValuesForSop: function() {         
		$('li.container #DaNumber').html('' + userDetailsJson.DaNumber);
		$('li.container #DiabetesType').html('' + userDetailsJson.DiabetesType);
		$('li.container #NDSSNumber').val(userDetailsJson.NDSSNumber);
		$('li.container #cardNumber').val(userDetailsJson.ConcessionCardNumber);			

		Date.prototype.toDateInputValue = (function() {
			var local = new Date(this);
			local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
			return local.toJSON().slice(0,10);
		});		
		/*var newDate;
		if(userDetailsJson.ConcessionCardExpiryDate != ""){
			var expDate = userDetailsJson.ConcessionCardExpiryDate;
			//expDate = expDate.split("-");
			newDate = new Date(expDate).toDateInputValue();
		}else{
			newDate = new Date().toDateInputValue();
		}*/

		$('li.container #cardExpDate').datepicker({
            format: "dd-mm-yyyy",
            startDate: '+1d'
        }); 
		 
		if(userDetailsJson.ConcessionCardExpiryDate != ""){			 
			$('li.container #cardExpDate').datepicker('update', userDetailsJson.ConcessionCardExpiryDate);			
		}

		
		var dropDownObject = $('li.container #cardType');
		dropDownObject.append($('<option>', {
			text: 'Select Card Type',
			value: 0
		}));
		var selectedVal=0;
		////console.log(userDetailsJson.concessionCardTypes);
		$.each(userDetailsJson.concessionCardTypes, function(i, item) {
			dropDownObject.append($('<option>', {
				text: item.ConcessionCardType,
				value: i+1
			}));
			if (item.ConcessionCardType == userDetailsJson.ConcessionCardType)
				selectedVal = i+1;
		});
		$("li.container #cardType option[value='" + selectedVal + "']").attr("selected", "selected");
		if(selectedVal==0){
			$('li.container #cardNumber').closest('div.shopeddit').hide();
			$('li.container #cardExpDate').closest('div.shopeddit').hide();
		}
		$(document).on("change", "li.container #cardType", function(e) {
			e.preventDefault();				
			if ($(this).val()==0) {
				$('li.container #cardNumber').closest('div.shopeddit').hide();
				$('li.container #cardExpDate').closest('div.shopeddit').hide();					
			}else{
				$('li.container #cardNumber').closest('div.shopeddit').show();
				$('li.container #cardExpDate').closest('div.shopeddit').show();					
			}
		});
        redirect.setValidationRules();	  
    },
	setValidationRules: function() {
		$.getScript("https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js")
		  .done(function( script, textStatus ) {				 
				$("li.container #shopForm").validate({
					errorClass: "inputError",					
					rules: {						
						cardNumber: {
							required: function(element){
								return $('li.container #cardType:visible option:selected').val()!=0;
							},
							maxlength: 16,
							alphanumeric: true
						},
						cardExpDate: {
							required: function(element){
								return $('li.container #cardType:visible option:selected').val()!=0;
							},
							FutureDate: true
						}
					} 
				});

				$.validator.addMethod("alphanumeric", function(value, element) {
				        return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value);
					}, "Concession card should be alphanumeric."
				); 

				$.validator.addMethod("FutureDate", function (value, element) { 
						var today = new Date().getTime(),
				        idate = value.split("-");
					    idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
					    return (today - idate) < 0 ? true : false;
				    }, "Concession card has expired."
				);

		  }).fail(function( jqxhr, settings, exception ) {
			$( "div.log" ).text( "Triggered ajaxError handler." );
		});
    }
};

var UserShopDetails = {
    fetchUserBigCommerceLoginDetails: function(ShopDetails) {
        $.orchestracmsRestProxy.doAjaxServiceRequest('DV_Shop_Service', ShopDetails, function(testStatus, json, xhr) {		
        	//console.log(json);		
            if (json.success) {				
				$("ul#nav-mobile > li#postlogin").show();
				if(!json.IsMember){							
					$("ul#nav-mobile > li#postlogin").html('<a>Welcome '+UserShopDetails.FirstNameLimit(json.FirstName)+'</a>');
					$( "ul.navbar-nav > li.join-nav").show();
				}
				userDetailsJson = json;
				// localStorage.setItem('uname',json.Email);
				// localStorage.setItem('pass',json.Password);
				var objLogin = {
					'uname':json.Email,
					'pass': json.Password
				};
				var userAgent = window.navigator.userAgent;
		        var checkIE = userAgent.indexOf("MSIE ");
		        if (checkIE > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
					window.name = JSON.stringify(objLogin);
				}
				////console.log(window.name);
				redirect.data.login = json.Email;
    			redirect.data.pass = json.Password;
				redirect.checkUserStatus();
            }

        }, null, true);
    },
	FirstNameLimit:function(strName){
		var strN='';
		if(strName.length > 13){
			for(var i=0;i< 12;i++)
			{
				strN=strN+strName[i];
			}
			strN=strN+"...";
			return strN;
		}
		return strName;
	}
};

function formatDate(dateInput) {    
	var newDate = dateInput.split("/").reverse().join("-");
    return newDate;
}

function disableShopHoveMenu(){
	//Change to hide Shop Popup
	var shopMenu = document.getElementsByClassName('dropdown shop');
	shopMenu[0].removeChild(shopMenu[0].children[1]);
	var element = shopMenu[0].children[0];
	element.href = storeURL;
	element.classList.remove("dropdown-toggle");
	setTimeout(function() { 
		element.classList.remove("bubble-text");
	}, 3000);
}

$(document).ready(function() {
	
	
	if(!window.location.pathname.match("/become-a-member-event-registration") && !window.location.pathname.match("/register-now-event-registration")){
		$(document).on("mouseover", "div.datepicker-dropdown", function(){
			$("li.shop").trigger('mouseover');
		});		
	}
	

	/*$(document).on("mouseout", "div.datepicker-dropdown", function(){
		$('li.container #cardExpDate').datepicker('hide');
	});*/
	
    if(CMS.user_type == 'Guest'){
		$("ul#nav-mobile > li#postlogin").hide();
		$('#sitemap #afterlogin').hide();

		disableShopHoveMenu();
		
		var shopLi = document.getElementsByClassName('dropdown shop');
		shopLi[0].addEventListener("click", function(){
			window.location.href = storeURL;
		});

	}else{
		$('#sitemap #beforelogin').hide();	
		$('head').append('<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.min.css">');
		$.getScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.min.js', function () {  });
		https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.min.js
		ShopDetails = {
			"action": 'fetchUserBigCommerceLoginDetails',
		};
		UserShopDetails.fetchUserBigCommerceLoginDetails(ShopDetails);
		$("ul#nav-mobile > li#prelogin").hide();
		$("ul.search-login > li:last").hide();		
		$( "ul.navbar-nav > li.join-nav").hide();
		//$( "li.mobile-nav a").eq(1).hide();
		
		disableShopHoveMenu();		
		$("#nav-mobile li.shop > a").on("click", function(ev){
			ev.preventDefault();
			$("div#showLoader").show();
			$("span#loading-content").html('Now logging you into the shop to personalise your experience.');				
			redirect.sendToBigCommerce();
		});
	}
	/*Remove login text*/
	/*var setTimeOutLogin = setInterval(checkLoginLink, 500);	
	function checkLoginLink(){
		if($("div.ocmsPortalLoginComponent > a#ocmsPortalLoginButton").length > 0){	
			$( "div.ocmsPortalLoginComponent > a#ocmsPortalLoginButton" ).hide();
			clearInterval(setTimeOutLogin);		
		}	 
	}*/

	
	/*Donate Tab related changes*/
	$(document).on("click", "ul#donateAmount > li:not(:last)", function(e) {	 
		$(".donate ul>li").removeClass('current');
		$(this).addClass('current');
		$('input#donate-amount').val('');
	});
	$(document).on("click", "input#donate-amount", function(e) {	 
		$(".donate ul>li").removeClass('current');		 
	});
	/*Donate Tab related changes*/


	/*Receipe related changes*/

	//console.log("Recipes from Diabetes Victoria");	

	var setTimeOutRecipe = setInterval(checkRecipeData, 1000);	
	function checkRecipeData(){
		if($("ul#recipecount > li").length > 0){
			$("ul#recipecount > li").each(function(){
				var spanElement = $(this).find('span:first');
				var nameElement = $(this).find('span:nth-child(2)');
				var oldVal = spanElement.html();
				var name = nameElement.html();
				spanElement.attr('base', oldVal);
				// if(oldVal == 0)			
				// 	$(this).remove();				
				if((isNaN(oldVal) && name =="") || (oldVal == "0" && name =="") || (oldVal == "" && name == "") || (oldVal == "" && name =="0")){
					$(this).remove();
				} else if(isNaN(oldVal) && name !==""){
					spanElement.html('');
				}
			});
			clearInterval(setTimeOutRecipe);
		}	 
	}

	setTimeout(function() { 
		//clearInterval(setTimeOutLogin);
		clearInterval(setTimeOutRecipe);
	 }, 10000);

	$(document).on("change", "input#recipeRange", function(e) {
		/*var rangeVal = $(this).val();
		// initial serve count
		// var serveCount = parseInt($('#perrangevalue').text());
		var serveCount = parseInt($('#ForServingCount').text());
		if(rangeVal == serveCount){
			handleRecipeRange();
			return;
		} else {
			var spanElement, baseVal, setVal;	
			$("ul#recipecount > li").each(function(){		
				spanElement = $(this).find('span:first');	
				baseVal = spanElement.attr('base');	
				if(baseVal !== "" && !isNaN(baseVal)){
					setVal = baseVal * rangeVal;					
					if(setVal === Number(setVal) && setVal % 1 !== 0){
						setVal = (Math.round(setVal/0.05)*0.05).toFixed(2);
					}
					$(this).find('span:first').html(''+setVal);
				}
			});
			$("#ForServingCount").html(''+rangeVal);
		}*/
		handleRecipeRange(false);
	});	

	function handleRecipeRange(setLocal){		
		// var serveCnt = parseInt($('#perrangevalue').text());
		var serveCnt = parseInt($('#ForServingCount').text());

		if(setLocal){
			localStorage.setItem('servecount', serveCnt);
			$('#recipeRange').val(serveCnt);
			if($('#perrangevalue') && $('#perrangevalue').length>0){
				var serveCnt = parseInt($('#perrangevalue').text());
				localStorage.setItem('servecount', serveCnt);
				$('#recipeRange').val(serveCnt);
			}
		} else {
			serveCnt = parseInt(localStorage.getItem('servecount'));
		}

		if(serveCnt && !isNaN(serveCnt)){
			// $('#recipeRange').val(serveCnt).trigger('change');
			//$('#recipeRange').val(serveCnt);
			var rangeVal = $('#recipeRange').val();	
			var spanElement, baseVal, setVal;	
			$("ul#recipecount > li").each(function(){		
				spanElement = $(this).find('span:first');	
				baseVal = spanElement.attr('base');	
				if(baseVal !== "" && !isNaN(baseVal)){
					setVal = baseVal * rangeVal;
					if(setVal === Number(setVal) && setVal % 1 !== 0){
						setVal = (Math.round(setVal/0.05)*0.05).toFixed(2);
					}
					$(this).find('span:first').html(''+setVal);
				}
			});
			$("#ForServingCount").html(''+rangeVal);
		}
	}
	
	/*Receipe related changes*/
	
    redirect.events();

    /*START: QAS address verification*/
    function callQasAddress(addressDetails){		 
		$('#qasModal').modal('show');
		$('#qasModal .modal-body').removeAttr('style');
		$("#qas").html("Validating address...");
		$.orchestracmsRestProxy.doAjaxServiceRequest('DV_OCMS_AddressVerification_Service', addressDetails, function(testStatus, json, xhr) {				
			if(json.success){
				$("#qas").html('');
				if(json.addressMatchSize >= 1){
					$.each(json.addressList,function(key, value){													
						$("#qas").append("<li style='list-style:none; padding:5px;'><input type='radio' name='qasAddress' value='"+value.addressMoniker+"'/>  "+value.addressName+"</li>");							
					});
					if(json.addressMatchSize > 15)
						$('#qasModal .modal-body').css({'overflow-y':'auto', 'height': '400px'});						
				}else{
					$('#qasModal').modal('hide');

					if(document.getElementById("collectionIdField") != null) {
						//console.log('No QAS address recommendations. This is a cloting collection page.');
						//console.log('Calling collection dates service with user entered postcode');
						actionData={};
						actionData["action"]="GetClothingCollectionDate";
						actionData["allowCallouts"]="true";
						actionData["PostCode"]=clothingDetails.getValueFromID('postCodeField');
						//console.log("sending postcode for collection dates", actionData);
						clothingDetails.callToSalesForce(actionData);
					}

				}					
			}else{					
				$('#qasModal').modal('hide');
			}				
		}, null, false);
    }

    var initialAddress = null;
    var addressCall = null;
	$(document).on("blur", "[rel=address], [rel=city], [rel=state], [rel=postcode]", function(e) {
	//$("#address, #city, #state, #postCode").on("blur", function(){
		addressCall=true;
		addressOtherCall=false;
		var validated = true;
		$("[rel=address], [rel=city], [rel=state], [rel=postcode]").each(function(){
			if($.trim($(this).val()) == ''){
				validated=false;
				return false;
			}			
		});
		////console.log(validated);
		if(validated==true){			
			var currentAddress = $("[rel=address]").val()+', '+$("[rel=city]").val()+', '+$("[rel=state]").val()+', AUS, '+$("[rel=postcode]").val();
			if(initialAddress == currentAddress){
				return false;
			}
			initialAddress = currentAddress;
			var addressDetails = {
				"action": 'getAddressList',
				"addressToSearch": currentAddress,
				"allowCallouts" : true				
			};
			callQasAddress(addressDetails);
		}
	});
 	
 	var initialAddressOther = null;
 	var addressOtherCall = null;
	$(document).on("blur", "[rel=addressother], [rel=cityother], [rel=stateother], [rel=postcodeother]", function(e) {
		addressCall=false;
		addressOtherCall=true;
	//$("#address, #city, #state, #postCode").on("blur", function(){
		var validated = true;
		$("[rel=addressother], [rel=cityother], [rel=stateother], [rel=postcodeother]").each(function(){
			if($.trim($(this).val()) == '' || (typeof $(this).val() == 'undefined') ){
				validated=false;
				return false;
			}			
		});
		////console.log(validated);
		if(validated==true){			
			// var currentAddress = $("[rel=address]").val()+', '+$("[rel=city]").val()+', '+$("[rel=state]").val()+', AUS, '+$("[rel=postcode]").val();
			var currentAddress = $("[rel=addressother]").val()+', '+$("[rel=cityother]").val()+', '+$("[rel=stateother]").val()+', AUS, '+$("[rel=postcodeother]").val();
			if(initialAddressOther == currentAddress){
				return false;
			}
			initialAddressOther = currentAddress;
			var addressDetails = {
				"action": 'getAddressList',
				"addressToSearch": currentAddress,
				"allowCallouts" : true				
			};
			callQasAddress(addressDetails);
		}
	});

	$(document).on("click", "#updateQas", function(e) {	
		if($(this).hasClass('updating')){
        	return false;
        }
        if($('input[name=qasAddress]:checked').length == 0){
        	alert("Please select an address from the list to update.");
        	return false;
        }        
        
        var originalText = $(this).text();
        var addressDetails = {
			"action": 'getAddressDetails',
			"addressMoniker": $('input[name=qasAddress]:checked').val(),						
			"allowCallouts" : true
		};
		$(this).text('Updating...').addClass("updating");  		
		$.orchestracmsRestProxy.doAjaxServiceRequest('DV_OCMS_AddressVerification_Service', addressDetails, function(testStatus, json, xhr) {			
			if(json.success && json.foundAddressDetails){
				if(addressCall){
					$("[rel=address]").val(json.street);
					$("[rel=city]").val(json.suburb);
					$("[rel=state]").val(json.stateCode);
					$("[rel=postcode]").val(json.postcode);				
				}else if(addressOtherCall){
					$("[rel=addressother]").val(json.street);
					$("[rel=cityother]").val(json.suburb);
					$("[rel=stateother]").val(json.stateCode);
					$("[rel=postcodeother]").val(json.postcode);
				}

				//console.log('Collection id field value = ' + $('#collectionIdField'));
				if(document.getElementById("collectionIdField") != null) {
					//console.log('This is a cloting collection page. Calling collection dates service');
					actionData={};
					actionData["action"]="GetClothingCollectionDate";
					actionData["allowCallouts"]="true";
					actionData["PostCode"]=clothingDetails.getValueFromID('postCodeField');
					//console.log("sending postcode for collection dates", actionData);
					clothingDetails.callToSalesForce(actionData);
				}				

			}
			$("#updateQas").text(originalText).removeClass("updating");
			$('#qasModal').modal('hide');			
		}, null, false);
	});
	/*END: QAS address verification*/

	// to initialize slider value on load
	var recipeTimer = setInterval(function(){ 
		handleRecipeRange(true);
		/*if($('#perrangevalue') && $('#perrangevalue').length > 0){
			clearInterval(recipeTimer);
		}*/
		if($("ul#recipecount > li") && $("ul#recipecount > li").length > 0){
			clearInterval(recipeTimer);
		}
	}, 1000);
});