/**
* @author hugo
* @description buy more credit popup, this is shared by schmap.it/new and /schmapit/promotion
**/
(function () {
    function showBuyMorePopup() {
        overlay.show({
            elm: $('buy_more_popup')
        });
    }
    var config = {
            url: 'https://' + location.host + '/ppay/jsp/cc_single_rt_credits.jsp'
        },
        msg = {
            wrongCreditcard: 'Wrong card number.',
            wrongCvv2: 'Wrong Card Security Code.',
            wrongExpireDate: 'Wrong Card Expiration Date.',
            failed: 'Unable to verify payment.  Please review and re-enter your information'
        },
        form = document.buymore,
        hint = $('pay_hint'),
        errorLogElm, postingHint,
		iframes = [];//store https iframe references, remove them if the user close the popup

    function showError(msg) {
        msg = msg || 'Sorry, some error happened, please try again!';
        if (!errorLogElm) {
            errorLogElm = document.createElement('span');
            errorLogElm.style.cssText = 'position:absolute;bottom:39px;left:5px;color:red;font-weight:bold;';
            var hint = $('pay_hint')
            hint.parentNode.insertBefore(errorLogElm, hint);
        }
        errorLogElm.innerHTML = msg;
        errorLogElm.style.display = 'block';
    }

    function hideError() {
        if (errorLogElm) {
            errorLogElm.style.display = 'none';
        }
    }

    function toggleNewCreditCard(isShow) {
        var elm = $('newCreditCard'),
            toggleButton = $('changeCreditCard'),
            display = '',
            action = '',
            text = '';
        if (!isShow) {
            display = 'none';
            action = 'remove';
            text = 'change';
            toggleButton.removeAttribute('active');
        } else {
            display = 'block';
            action = 'add';
            text = 'revert';
            toggleButton.setAttribute('active', 'active');
        }
        toggleButton.innerHTML = text;
        elm.style.display = display;
        cssjs(action, elm, 'another-creditcard');
        hideError();
    }
    $('changeCreditCard').onclick = function () {
        toggleNewCreditCard(!this.getAttribute('active'))
    };

    function restoreState() {
        var elm = $('existedCreditCard');
		postingHint && postingHint.hide();
        form.style.visibility = 'visible';
		if(elm){
			if(schmapit.creditCardNumber){
				elm.style.display = 'block';
			}else{
				elm.style.display = 'none';
			}
		}
        toggleNewCreditCard(!schmapit.creditCardNumber);
    }
	
	function createIframe(url, onload, beforeAppend) {
	    var iframe = document.createElement("iframe");
		iframe.src = url || 'about:blank';

		if(!onload){return;}
		if (iframe.attachEvent){
			iframe.attachEvent("onload", onload);
		} else {
			iframe.onload = onload;
		}
		if(typeof beforeAppend(iframe)){
			beforeAppend(iframe);
		}
		document.body.appendChild(iframe);
        return iframe;
	}

    function hanldeSuccess(data) {
	    if (paypal.listener && paypal.listener['success']) {
			var arr = paypal.listener['success'];
			for (var i = 0, l = arr.length; i < l; i++) {
				var item = arr[i];
				if (typeof item === 'function') {
					item(data);
				}
			}
		}
		schmapit.remainingCredits = data.remaining_retweet_credit; //update the remaining credits
		var remainNumberElm = $('remain_number');
		if(remainNumberElm){
			remainNumberElm.innerHTML = schmapit.remainingCredits;
		}
		schmapit.creditCardNumber = data.creditCardNumber;
		postingHint.call('The payment has been successfully commited.', {
			src: '/image/success.png',
			width: 37,
			height: 38
		});
	}
	
	function check(url, data, maxTimes){
	    var i = 0;
		function handleError(msg){
		    restoreState();
			showError(msg || 'Sorry, The payment process has failed, please try again!');	
		}
	    function step(){
			if(maxTimes < i++){
				handleError('Sorry, The payment process has failed, please try again!');			
				return;
			}
			ajax({
				url: url + '?' + new Date().getTime(),//in case of cache
				onSuccess: function(resp){
					if(!resp){
						setTimeout(step, 1000);
						return;
					}
					var code = resp.code;
					if(code === '0'){
					    resp.creditCardNumber = data.creditCardNumber;
						hanldeSuccess(resp);
					} else {
						if(code === 'null'){
							setTimeout(step, 1000);
						}else{
							handleError(resp.message);
						}
					}
				},
				onError: function(){
					setTimeout(step, 500);
				},
				timeout: 2000,
				onTimeout: function(xhr){
					setTimeout(step, 500);
					try{xhr.abort();}catch(e){}
				}
			});
	    }
	    step();
	}
	
	function handlePaypal(data){
	    //alert('onload');
		var url = queryUrl = 'http://' + location.host + '/ppay/jsp/payment_status.jsp';
		check(url, data, 10);
	}
	function paypal(data) {
		data.format = 'plain';
		var scheme = 'https://';
		if(location.host.indexOf('dev') > -1){
			scheme = 'http://';
		}
		var url = scheme + location.host + '/ppay/jsp/cc_single_rt_credits.jsp' + serializeJson(data) + '&timestamp=' + new Date().getTime();//config.url + serializeJson(data),
		iframe = createIframe(url, function(){
		    handlePaypal(data);
		}, function(iframe){
			iframe.style.cssText = 'position:absolute;top:-2222px;';
		});
		postingHint = postingHint || new Working(form.parentNode, 'paying');
        postingHint.call('posting your request, please wait...');
        form.style.visibility = 'hidden';
	}
	
    window.paypal = paypal;
    paypal.addlistener = function (type, fn) {
        paypal.listener = paypal.listener || {};
        var listener = paypal.listener;
        listener[type] = listener[type] || [];
        listener[type].push(fn);
    };

    function filterNumber(number) {
        number = number.toString();
        return number.replace(/\-|\s+/g, ''); //in case user type in "-" 
    }
    var creditCardReg = /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|622((12[6-9]|1[3-9][0-9])|([2-8][0-9][0-9])|(9(([0-1][0-9])|(2[0-5]))))[0-9]{10}|64[4-9][0-9]{13}|65[0-9]{14}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})*$/,
        //this reg covers all major credit cards: American Express (Amex), Discover, Mastercard, and Visa.
        nonDigitReg = /[^0-9\- ]/;
    var creditcard = {
        getValidCardNumber: function (number) {
            number = filterNumber(number);
            if (!number || nonDigitReg.test(number)) {
                return 0;
            }
            return creditCardReg.test(number) && number;
        },
        getValidExpireDate: function (number) {
            var year, month, currentYear, currentMonth, now, expireDate;
            number = filterNumber(number);
            if (number.length !== 4) {
                return 0;
            }
            year = +(20 + number.substring(2, 4)); //use + to convert string to number
            month = +number.substring(0, 2);
            now = new Date();
            expireDate = new Date(year, month - 1);
            currentYear = now.getFullYear();
            currentMonth = now.getMonth();
            if (year < currentYear || month > 12 || now >= expireDate) {
                return 0;
            }
            return '' + month + year;
        },
        getValidCcv2: function (ccv2) {
            ccv2 = filterNumber(ccv2);
            return (ccv2.length === 3 || ccv2.length === 4) && ccv2;
        }
    };
    var buyLinkAttr = 'from-link-id';

    function handleBuyMore() {
        $('buy_more_popup').setAttribute(buyLinkAttr, this.id);
        restoreState();
        showBuyMorePopup();
    }['buy_more', 'buy_more_2', 'buy_more_3'].forEach(function (id) {
        var elm = $(id);
        if (elm) {
            elm.onclick = handleBuyMore;
        }
    });

    function getRadioValue(radios) {
        var l = radios.length,
            radio;
        while (l--) {
            var radio = radios[l];
            if (radio.checked) {
                return radio.value;
            }
        }
        return '';
    }
    //register event listener
    //listen form submit event
    form.onsubmit = function () {
        try {
            var self = this,
                creditCardNumber = self.creditCardNumber.value,
                expireDate = self.card_date.value,
                cvv2 = self.cvv2.value,
                quantity = self.quantity.value,
                amount = getRadioValue(self.totalcredit);

            if (window.schmapit && schmapit.creditCardNumber && !$('changeCreditCard').getAttribute('active')) {
                var data = {
                    creditCardNumber: schmapit.creditCardNumber,
                    amount: amount,
                    quantity: quantity,
                    creditCardSource: schmapit.creditCardSource
                };
                paypal(data);
                return false;
            }
            //check the credit card number whether is valid
            creditCardNumber = creditcard.getValidCardNumber(creditCardNumber);
            if (!creditCardNumber) {
                showError(msg.wrongCreditcard);
                try {
                    self.creditCardNumber.focus();
                } catch (e) {}
                return false;
            }
            //check expire date
            expireDate = creditcard.getValidExpireDate(expireDate);
            if (!expireDate) {
                i
                showError(msg.wrongExpireDate);
                try {
                    self.card_date.focus();
                } catch (e) {}
                return false;
            }
            //check cvv2
            cvv2 = creditcard.getValidCcv2(cvv2);
            if (!cvv2) {
                showError(msg.wrongCvv2);
                try {
                    self.cvv2.focus();
                } catch (e) {}
                return false;
            }
            var data = {
                cvv2Number: cvv2,
                creditCardNumber: creditCardNumber,
                expDateMonth: expireDate.substring(0, 2),
                expDateYear: expireDate.substring(2),
                amount: amount,
                quantity: quantity
            };
            paypal(data);
        } catch (e) {
            console.log(e);
        }
        return false;
    };

    function setCreditsByAmount(amount) {
        var number, paypalLink = $('paypal_link');
        switch (amount) {
        case '50':
            number = 10;
            break;
        case '90':
            number = 20;
            break;
        case '120':
            number = 30;
            break;
        default:
            return;
        }
        form.quantity.value = number;
        hint.innerHTML = '<b>' + number + ' credits</b> for a total purchase of $' + amount + '.00: ';
		if(paypalLink){
		    paypalLink.href = 'https://www.schmap.it/ppay/jsp/setec_rt_credits.jsp?amount=' + amount + '&quantity=' + number;
		}
		
    }
    setCreditsByAmount(getRadioValue(form.totalcredit));

    function warn(elm) {
        var action = 'add',
            step = 4,
            i = 0;

        function toggleBorder() {
            action = action === 'add' ? 'remove' : 'add';
            cssjs(action, elm, 'warn-red');
            if (i++ >= step) {
                return;
            }
            setTimeout(toggleBorder, 300);
        }
        toggleBorder()
    }

    //listen creditcard infomation inputs change
    var changeListeners = [creditcard.getValidCardNumber, creditcard.getValidExpireDate, creditcard.getValidCcv2],
        errorMsg = [msg.wrongCreditcard, msg.wrongExpireDate, msg.wrongCvv2];
    ['creditCardNumber', 'card_date', 'cvv2'].forEach(function (item, index) {
        var input = form[item];
        input.onchange = function () {
            var fn = changeListeners[index],
                value = fn(this.value);
            if (!value) {
                showError(errorMsg[index]);
                warn(this);
            } else {
                hideError();
            }
        };
    });
    //listen radio button change event;
    (function () {
        var radios = form.totalcredit,
            radio, l = radios.length;;
        while (l--) {
            radio = radios[l];
            radio.onchange = function () {
                setCreditsByAmount(this.value);
            };
        }
    })();
    var trigger = $('terms_popup_trigger');
    if (trigger) {
        trigger.onclick = function () {
            overlay.show({
                elm: $('terms_use')
            });
            return false;
        };
    }
    var closeButton = $('close_buymore');
    if (closeButton) {
        closeButton.onclick = function () {
            var tweetPopup = $('tweet_popup');
            var fromId = $('buy_more_popup').getAttribute(buyLinkAttr);
            switch (fromId) {
            case 'buy_more_2':
                overlay.show({
                    elm: tweetPopup
                });
                break;
            case 'buy_more_3':
                overlay.show({
                    elm: $('tweet_popup_promotion')
                });
                break;
            default:
                overlay.hide();
            }
            return false;
        };
    }
    window.creditcard = creditcard; //expose to public
    //add listener for buy more credits
    paypal.addlistener('success', function (data) {
        var arr = ['popup_remain_credits', 'popup_remain_credits_2'];
		arr.forEach(function(item){
		    var elm = $(item);
			 if (elm) {
				elm.innerHTML = data.remaining_retweet_credit;;
			}
		});
    });
})();
