var querystring = (function () {
    	var _ = {};
    	var params  = {};
        var init = function () {
        	buildObj();
        };
        //-- private
        var buildObj = function () {
        	var _querystring = document.location.search.slice(1);
            var _params = _querystring ? _querystring.split('&') : [];
            for( var i = 0; i < _params.length; i++ ) {
            	var parts = _params[i].split('=');
                if ( parts.length == 1 )
                	parts.push('true');
                params[ parts[0] ] = decodeURIComponent( parts[1] );
            }
        };
        //-- public
        _.get = function ( param ) {
        	return params[param] || false;
        };
        _.getAll = function () {
        	return params;
        };
        _.remove = function ( param ) {
        	delete params[param];
        };
        _.set = function ( param, val ) {
        	params[param] = val ? val.toString() : 'true';
        };
        _.build = function ( obj ) {
        	var _params = obj ? obj : params;
        	var str = [];
            for (var cv in _params)
                str.push( cv + '=' + _params[cv] );
            return '?' + str.join('&');
        };
		init();
        return _;
	})();

	var payment_module = (function ($) {
    	
        var _ = {};
    
    	var init = function () {
        	utils.setConfig();
        	events.init();
            utils.fixHeights($('.row.checked'));
            utils.setDefault();
        };
        
        var config = _.config = {};
        
        var utils = _.utils = {
        	setConfig: function () {
	            config.container		= $('.payment-select-module-container');
            	config.rows				= config.container.find('.row') ;
            	config.left				= config.container.find('.left') ;
				
				//identify links in payment module
				config.links			= config.rows.find('a');
                config.radios			= config.left.find('input[type=radio]');
                config.top_bubble		= top_bubble();
                config.checkout_bubble	= utils.isPaypal() ? checkout_bubble(_) : false;
                
                // JCA 06/20/2011 
                config.checkout_placecard = utils.isPlacecard() ? checkout_bubble(_) : false;
                config.def				= utils.getPaymentMethodName(); 
                
            },
            setRow: function (row) {

            	$(row).addClass('checked').siblings().removeClass('checked');
                $(row).find('input[type=radio]').attr('checked', true);

                $(row).siblings().find('.right input, .right select, .right textarea').attr('disabled', true);
				$(row).find('.right input, .right select, .right textarea').removeAttr('disabled');
                $('.payment_type_message').text(
                	$(row).find('.payment_name').text()
                );
                
                // To override the text on the UI when user change the payment type.                               
                $('#payment_type_message').text($(row).find('.payment_name').text() + ':');
                $('#payment_type_message2').text($(row).find('.payment_name').text() + ':');
                
                utils.fixHeights(row);
               
                if (config.checkout_bubble ){
                 	config.checkout_bubble.utils.update(row);
                }
            },
            fixHeights: function (row) {
            	var rht = $(row).find('.right').height();
                var lht = $(row).find('.left').height();
                $(row).find('.left, .right').height( Math.max(rht, lht) );
                $(row).siblings().find('.left, .right').height('auto');
            },
            setDefault: function () {
            	utils.setRow( $('.row:has(input[value=' + config.def + '])') );
            },
            isPaypal: function () {

				if(document.getElementById('jsPaymentMethod') != null){
	            	if (document.getElementById('jsPaymentMethod').value == 'paypal'){
	            		return true;
	            	}else{
	            		return false;
	            	}
	            	
            	}else{
            		return false;
            	}
            	
            },
			// JCA 06/26/20111
            isPlacecard: function () {

				if(document.getElementById('jsPaymentMethod') != null){
	            	if (document.getElementById('jsPaymentMethod').value == 'placd_card' && document.getElementById('rewards_code').value != ''){
	            		return true;
	            	}else{
	            		return false;
	            	}
	            	
            	}else{
            		return false;
            	}
            	
            },
            getPaymentMethodName: function () {
           	
            	// Return either credit_card, bml, paypal, place_card, or empty string if not found.
            	if(document.getElementById('jsPaymentMethod') != null){
            		return document.getElementById('jsPaymentMethod').value;
            	}else{
            		return '';
            	}
            }
        };
        
        var events = {
        	init: function () {
				config.links.click(events.links.click);
				// JCA 06/20/2011
            	//config.rows.click(events.rows.click);
            	config.left.click(events.left.click);
                config.radios.change(events.radios.change);
            },
	    	links: {
				click: function (e) {
					e.stopPropagation(); // stop click event propagation for row
				}
	    	},
	    	
	    	// JCA 06/20/2011
	    	left: { 
	    		click: function () {
	    		
	            	if (config.checkout_bubble) {
		        	   	setTimeout(function(){
						   	if ($('input[name=payment_method]:checked').val() != 'paypal'){
				    	   		confirmPopup(_);
				        	}
				    	});
	            	} else {
		            	if (config.checkout_placecard) {
		            		setTimeout(function(){
						  		if ($('input[name=payment_method]:checked').val() != 'placd_card'){
				           			confirmPopupPlacecard(_);
				           		}
						   	});
						}
					}
    	        	utils.setRow($(this).parent());
	    		}
	    	},
            rows: {
            	click: function () {
	            	if (config.checkout_bubble){
		    	       	//greyOut(true);
	    	        		
		    	       	// This is a hack that work around for FF and IE that not able to cover the bottom part of the page with greyout.
		        	   	setTimeout(function(){
						//greyOut(true)
						    		
						// Only file the confirm box if user is not pre-selected PP.
						   	if ($('input[name=payment_method]:checked').val() != 'paypal'){
				    	   		confirmPopup(_);
				        		}
				    		});
	            	} 
	            	
	            	utils.setRow(this);
	            	
	            }
            },
            radios: {
            	change: function () {
                    utils.setRow($(this).parent().parent());
                }
            }
        };
        
        $(init);
        
        return _;
        
    })(jQuery);
    
    var checkout_bubble = function (parent) {
    	var init = function () {
        	config.$container.hide();
            events.init();
            
        };
        var config = {
        	$container: $('#checkout_bubble_container_02'),
            $yes: $('#bubble_yes'),
            $no: $('#bubble_no'),
            $form: $( document.CardInfo ),
            offset: 59,
            accepted: false
        };
        var utils = {
        	update: function (node) {
            	if (utils.checkSelection(node) && !config.accepted) {
                	//config.$container.css('top', utils.getTop(node)).show();
                    config.$form.addClass('disabled');
                } else {
                	config.$container.hide();
                    config.$form.removeClass('disabled');
                }
            },
            getTop: function (node) {
            	return $(node).offset().top - $(node).parent().offset().top - config.offset
            },
            checkSelection: function (node) {
            	return !$(node).is(':has(input[value=paypal])');
            },
            formEnabled: function () {
            	return config.formEnabled;
            }
        };
        var events = {
        	init: function () {
            	config.$yes.click(events.yes);
                config.$no.click(events.no);
            },
            yes: function () {
            	config.$container.hide();
                config.accepted = true;
                
                
				//greyOut(false);

				
            },
            no: function () {
            	parent.utils.setDefault();
            	
				//greyOut(false);
				confirmPopup(parent);
            }
        };
        init();
        return {utils:utils};
    };
    
    var top_bubble = function () {
    
	    if ($("#review-top").length == 0){
			return;
		}
    
    	var init = function () {
        	events.init();
        };
        var config = {
        	container: $('#checkout_bubble_container'),
            closeBtn: $('#ch_closeWindow a'),
         
         	targetObjTop: $("#review-top").offset().top
   
        };
        var utils = {};
        var events = {
        	init: function () {
            	config.closeBtn.click(events.btnBubble.click),
            	config.container.css({top: config.targetObjTop - 162}); //hmm, kind of hacky...
            },
            btnBubble: {
            	click: function () {
            		config.container.hide()
            	}
            }
        };
        init();
        return {config:config};
    };
    
    /*
    var greyOut =  function (boolLight){
    
    	alert("GrayOut");
    	return false;
    
    };
   
    
    var greyOut =  (function (boolLight){
    
    	var isGrey =  boolLight;
    	var $box = $("<div></div>");
    	if(isGrey){
    		$box.addClass("greyCover");
        	$("body").prepend($box);
        	$box.fadeTo("fast", 0.8);
        	$box.css(
        			{'height': $(document).height(),
        			 'width': $(document).width()
        		});
			var left = $('#checkout_bubble_container').offset().left;  
        	$('#checkout_bubble_container').appendTo('body').css('left', left);
			var top = $('#checkout_bubble_container_02').offset().top;
			var left = $('#checkout_bubble_container_02').offset().left;
			$('#checkout_bubble_container_02').appendTo('body').css({top:top, left:left});
			
			        	
        	
        	//alert ("isGrey: " + isGrey)
        	return isGrey;    	
    	}
    	else{
    		//alert("isGrey" + isGrey)
    		$(".greyCover").css({'display': 'none'});
    	}
    	
    });
    */
   
   /* 
    $(function(){
    	setTimeout(function(){
    		greyOut(true)
    	});
    });	
    */
    
    var confirmPopup = function (parent) {

    	 var userResponse = confirm('Are you sure? Changing your payment method at this stage will cause your PayPal information to be abandoned. Are you sure you want to change payment method?');
    	 
    	 if(userResponse){
    	 					
            var tcpCCTransUpdateCmd = document.getElementById("tcpCCTransUpdateCmd").value;
            tcpCCTransUpdateCmd = tcpCCTransUpdateCmd + "&jsPaymentMethod=" + $('input[name=payment_method]:checked').val();
			setTimeout(function(){ window.location = tcpCCTransUpdateCmd; }, 0);
			
			return true;
    	 }else{
    	 	
    	 	parent.utils.setDefault();
    	 }
   
    }	
    
    var confirmPopupPlacecard = function (parent) {

    	 var userResponse = confirm('Are you sure? Changing your payment method at this stage will cause your Place Card information to be abandoned. Are you sure you want to change payment method?');
    	 
    	 if(userResponse){
    	 					
            var promotionCodeManage = document.getElementById("promotionCodeManage").value;
            promotionCodeManage = promotionCodeManage + "&removeAllPP=true&removePlacePoints=y&URL=OrderDisplay&jsPaymentMethod=" + $('input[name=payment_method]:checked').val();
			setTimeout(function(){ window.location = promotionCodeManage; }, 0);
			
			return true;
    	 }else{
    	 	
    	 	parent.utils.setDefault();
    	 }
   
    }    
