// - ///////////////////////////////////////////////////////////////////////
// - COURSES MODULE
// - ///////////////////////////////////////////////////////////////////////
//fields
beCoursesModule.prototype._transport;
beCoursesModule.prototype._channelId = 'site.courses';
beCoursesModule.prototype._isCheckout;
beCoursesModule.prototype._isCheckoutReview;
beCoursesModule.prototype._isCheckoutCompleted;
beCoursesModule.prototype._queryParams;
beCoursesModule.prototype._cartCourses;
beCoursesModule.prototype._cartTotal;

//constructor
function beCoursesModule() {}

beCoursesModule.prototype.initialize = function(transport) {
    this._transport = transport;
    this._cartCourses = new Array();
    this._cartTotal = 0;

    //make sure we have the cart div on the page
    if ($('cart')) {
        //set variables
        this._isCheckout = (window.location.pathname.indexOf('checkout') != -1) ? true : false;
        this._queryParams = window.location.search.toQueryParams();

        //attach event observers to all links that have a class of "addToCart"
        var me = this;
        $$('.addToCartButton').each(function(a) {
            a.observe('click', me.cartAddClick.bindAsEventListener(me));
        });

        //check queryparams for itemid and qty to see if we're looking to add to the cart
        //by passing information via the querystring
        if (this._queryParams.itemid) {
            this.cartAddItem(this._queryParams.itemid);
        } else {
            this.cartLoad();
        }

        //configure the checkout if we're there
        if (this._isCheckout) {
            //ensure that we're in secure mode
            var location = window.location.toString().toLowerCase();
            var isSecure = ("https:" == document.location.protocol) ? true : false;
            var isDev = (location.indexOf('http://localhost/') != -1 || location.indexOf('http://devmembers.') != -1) ? true : false;
            var secureUrl = window.location.toString().replace('http://', 'https://');

            if (!isSecure && !isDev) {
                window.location = secureUrl;
            } else {
                this.checkoutConfigure();
            }
        }
    }
}

beCoursesModule.prototype.cartLoad = function(){
    //don't load the cart if we we're in review mode
    if(!this._isCheckoutReview){
        var request = {}
        this._transport.transmitRequest(this._channelId, 'getcart', request, this.cartLoadCompleted.bindAsEventListener(this));	
    }
}

beCoursesModule.prototype.cartLoadCompleted = function(objResponse){
    $('cartFull').update();
    $('cartEmpty').hide();
    
	if (objResponse.cart){
	    if(objResponse.items && objResponse.items.length > 0){
	        var cartDiv = new Element('div');	        	        
	        var cartTotal = 0;
	        var cartTable = new Element('table');
	        var cartTableBody = new Element('tbody');
	        
	        for(var x=0; x < objResponse.items.length; x++){
	            var cartItem = objResponse.items[x];
	            var cartTableRow = new Element('tr').addClassName('cart-item');
	            var cartTableCellName = new Element('td');
	            var cartTableCellPrice = new Element('td');
	            var removeLink = new Element('a', {'class':'remove', 'rel': cartItem.ItemId}).update('remove');
	            removeLink.writeAttribute('course',cartItem.name.gsub("'",""));
	            removeLink.writeAttribute('price',cartItem.price);
	            removeLink.observe('click', this.cartRemoveClick.bindAsEventListener(this));

	            cartTableCellName.appendChild(new Element('div').update(cartItem.name));
	            cartTableCellName.appendChild(removeLink);
	            
	            cartTableCellPrice.appendChild(new Element('div', {'class':'price'}).update(BEFormatCurrency(cartItem.price)));

	            cartTableRow.appendChild(cartTableCellName);
	            cartTableRow.appendChild(cartTableCellPrice);	  
	            cartTableBody.appendChild(cartTableRow);
	            
	            //increment our total in the cart
	            cartTotal += (cartItem.price * cartItem.Qty);
	        }
	        
	        //add the totals row
	        var cartTotalRow = new Element('tr').addClassName('cart-total');
	        var cartTotalCell1 = new Element('td', {'class':'total'}).update('Total');
	        var cartTotalCell2 = new Element('td');
	        var cartTotalDiv = new Element('div', {'class':'price'}).update('<strong>' + BEFormatCurrency(cartTotal) + '</strong>');
	        cartTotalCell2.appendChild(cartTotalDiv);
	        cartTotalRow.appendChild(cartTotalCell1);
	        cartTotalRow.appendChild(cartTotalCell2);
	        cartTableBody.appendChild(cartTotalRow);
	                  
	        cartTable.appendChild(cartTableBody);
	        cartDiv.appendChild(cartTable);	        

	        //add button to checkout now that we have items in the cart, but only if we're not in checkout
	        if(!this._isCheckout){
	            var buttonBase = new Element('div', {'class':'cart-button-checkout'});
	            var buttonText = new Element('span');
	            var buttonLink = new Element('a', {href: '/courses/checkout/'}).update('Checkout &raquo;');
    	        
	            buttonText.appendChild(buttonLink);
	            buttonBase.appendChild(buttonText);
	            cartDiv.appendChild(buttonBase);
	        }
	        
	        $('cartLoading').hide();
	        $('cartFull').appendChild(cartDiv);
	    }else{
	        //cart is emtpy
	        $('cartLoading').hide();
	        $('cartEmpty').show();	        
	        
	        if(this._isCheckout){
	            window.location = '/courses/';
	        }
	    }
	    
	    //anytime the cart was loaded scroll to the top so the user can see the cart
	    window.scrollTo(0,0);
	}  
};

beCoursesModule.prototype.cartAddClick = function(event){  
    var link = event.element();
    $('cartLoading').show();
    this.cartAddItem(link.readAttribute('rel'));
    be_globalSiteFramework.trackEvent('Courses','Add to cart', link.readAttribute('course'),link.readAttribute('price'));
};

beCoursesModule.prototype.cartAddItem = function(itemId){
    var request = {mode:'update',itemId:itemId,qty:1};
    this._transport.transmitRequest(this._channelId, 'addupdatecartitem', request, this.cartLoad.bindAsEventListener(this));
};

beCoursesModule.prototype.cartRemoveClick = function(event){
    var link = event.element();
    $('cartLoading').show();
    this.cartRemove(link.readAttribute('rel'));
    be_globalSiteFramework.trackEvent('Courses','Remove from cart', link.readAttribute('course'),link.readAttribute('price'));
};

beCoursesModule.prototype.cartRemove = function(itemId){
    var request = {mode:'delete',itemId:itemId,qty:0};
    this._transport.transmitRequest(this._channelId, 'addupdatecartitem', request, this.cartLoad.bindAsEventListener(this));
};

beCoursesModule.prototype.checkoutConfigure = function(){
    if($('newContinue') != null){
        $('newContinue').observe('click', this.checkoutRegister.bind(this));        
        $('signinContinue').observe('click', this.checkoutSignIn.bind(this));
    }
    
    if($('checkoutLogout') != null){    
        $('checkoutLogout').observe('click', this.checkoutLogout.bind(this));
        $('infoInsideUS').observe('click', this.checkoutToggleUS.bind(this));
        $('infoOutsideUS').observe('click', this.checkoutToggleUS.bind(this));
        $('infoReview').observe('click', this.checkoutReview.bind(this));
        $('reviewEditBilling').observe('click', this.checkoutReviewEdit.bind(this));
        $('reviewEditPayment').observe('click', this.checkoutReviewEdit.bind(this));
        $('reviewCouponApply').observe('click', this.checkoutApplyCoupon.bind(this));
        $('reviewComplete').observe('click', this.checkoutFinalize.bind(this));
    }
    
    if($('savedAddress') != null){
        $('infoFirstName').value = $('bFirstName').value;
        $('infoLastName').value = $('bLastName').value;
        $('infoAddress1').value = $('bAddressLine1').value;
        $('infoAddress2').value = $('bAddressLine2').value;
        $('infoCity').value = $('bCity').value;
        $('infoZip').value = $('bZipPostalCode').value;
        $('infoCountry').value = $('bCountry').value;
     
        if($('bCountry').value == 'United States'){
            $('infoState').value = $('bStateProvince').value;            
            $('infoStateDiv').show();
        }else{
            $('infoRegion').value = $('bStateProvince').value;
            $('infoRegionDiv').show();            
            $('infoCountryDiv').show();
        }   
    }else {
        if($('infoStateDiv') != null){
            $('infoStateDiv').show();
            $('infoCountry').value = 'United States';
        }
    }
    
    //goal tracking - check for logged in vs. logged out
    if($('newContinue') != null){
        be_globalSiteFramework.trackPageview('/courses/checkout/login-or-create');
    }else{
        be_globalSiteFramework.trackPageview('/courses/checkout/billing-info');
    }
};

beCoursesModule.prototype.checkoutToggleUS = function(event){
    event.stop();
    if(event.element().identify() == 'infoInsideUS'){
        $('infoCountry').value = 'United States';
        $('infoCountryDiv').hide();
        $('infoRegionDiv').hide();
        $('infoStateDiv').show();
    }else{
        $('infoStateDiv').hide();
        $('infoRegionDiv').show();
        $('infoCountryDiv').show();
    }
};

beCoursesModule.prototype.checkoutLogout = function(event){
    be_globalSiteFramework.logout(this.checkoutLogoutCompleted.bind(this));
};

beCoursesModule.prototype.checkoutLogoutCompleted = function(objResponse){    
    window.location.reload();
};

beCoursesModule.prototype.checkoutRegister = function(event){
    event.stop();
    var errorList = '';

    //validate only existence of information and let server-side to more rigit valiation
    if($('newFirstname').value.length == 0){errorList += '<li>Enter your first name</li>';}
    if($('newLastname').value.length == 0){errorList += '<li>Enter your last name</li>';}
    if($('newUsername').value.length == 0){errorList += '<li>Enter a username</li>';}
    if($('newPassword').value.length == 0){errorList += '<li>Enter a password</li>';}
    if($('newPasswordConfirm').value.length == 0){errorList += '<li>Re-type your password</li>';}
    if($('newPassword').value != $('newPasswordConfirm').value){errorList += '<li>Your passwords don\'t match</li>';}
    if($('newEmail').value.length == 0){errorList += '<li>Enter a valid e-mail address</li>';}
    
    if(errorList.length > 0){
        $('newError').update('<ul>' + errorList + '</ul>');
        $('newError').show();
    }else{
        $('newError').hide();
        
        var request = {
            firstname:$('newFirstname').value,
            lastname:$('newLastname').value,
            username:$('newUsername').value,
            password:$('newPassword').value,
            email:$('newEmail').value
        };
        this._transport.transmitRequest(this._channelId, 'createaccount', request, this.checkoutRegisterCompleted.bindAsEventListener(this));        
    }    
};

beCoursesModule.prototype.checkoutRegisterCompleted = function(objResponse){
    if(objResponse.result == 'ok'){
        window.location.reload();
    }else{
        $('newError').update(objResponse.message);
        $('newError').show();        
    }
};

beCoursesModule.prototype.checkoutSignIn = function(event){
    event.stop();
    if($('signinUsername').value.length == 0 || $('signinPassword').value.length == 0){
        $('signinError').update('Please enter both your username and password');
        $('signinError').show();
    }else{
        $('signinError').hide();
        be_globalSiteFramework.login($('signinUsername').value, $('signinPassword').value, this.checkoutSignInCompleted.bind(this));
    }
};

beCoursesModule.prototype.checkoutSignInCompleted = function(objResponse){
    if(objResponse.result == 'ok'){
        window.location.reload();
    }else{
        $('signinError').update('Unable to validate your login information. Please double check your username and password and try again');
        $('signinError').show();
    }
};

beCoursesModule.prototype.checkoutReview = function(event){
    if(event != null){event.stop();}
    var errorList = '';
    
    //validate only existence of information and let server-side to more rigit valiation
    if($('infoFirstName').value.length == 0){errorList += '<li>Enter your first name</li>';}
    if($('infoLastName').value.length == 0){errorList += '<li>Enter your last name</li>';}
    if($('infoAddress1').value.length == 0){errorList += '<li>Enter your billing address</li>';}
    if($('infoCity').value.length == 0){errorList += '<li>Enter your billing city</li>';}
    if($('infoStateDiv').style.display != 'none'){
        if($('infoState').value.length == 0){errorList += '<li>Select your state</li>';}
    }else{
        if($('infoRegion').value.length == 0){errorList += '<li>Enter your region</li>';}
    }
    
    if($('infoZip').value.length == 0){errorList += '<li>Enter your zip/postal code</li>';}
    if($('infoCountry').value.length == 0){errorList += '<li>Select your country</li>';}
    if($('infoCCTypeId').value.length == 0){errorList += '<li>Select the type of card to use</li>';}    
    if($('infoCCName').value.length == 0){errorList += '<li>Enter the name as it appears on your card</li>';}
    if($('infoCCNumber').value.length == 0){errorList += '<li>Enter the card number</li>';}
    if($('infoCCExpMo').value.length < 2){errorList += '<li>Enter the expiration month as two digits</li>';}
    if($('infoCCExpYear').value.length < 4){errorList += '<li>Enter the expiration year as four digits</li>';}
    if($('infoCCCode').value.length == 0){errorList += '<li>Enter the credit card security code found either on the front (AMEX) or back of the card</li>';}
    
    if(errorList.length > 0){
        $('infoError').update('<ul>' + errorList + '</ul>');
        $('infoError').show();
    }else{
        $('infoError').hide();
        this._transport.transmitRequest(this._channelId, 'loadcartforcheckout', {ignoreJSON:true}, this.checkoutReviewCompleted.bindAsEventListener(this));        
    }
};

beCoursesModule.prototype.checkoutReviewCompleted = function(objResponse){
    $('cart').hide();
    $('checkoutInfo').hide();
    $('checkoutReview').show();
    
    var billingInfo = $('infoFirstName').value + ' ' + $('infoLastName').value + '<br/>';
    billingInfo += $('infoAddress1').value + '<br/>';
    billingInfo += ($('infoAddress2').value.length > 0) ? $('infoAddress2').value + '<br/>' : '';
    billingInfo += $('infoCity').value + ', ';
    billingInfo += ($('infoStateDiv').style.display != 'none') ? $('infoState').value + ' ' : $('infoRegion').value + ' ';
    billingInfo += $('infoZip').value + '<br/>' + $('infoCountry').value;
    $('reviewAddress').update(billingInfo);
    
    var ccInfo = $('infoCCTypeId')[$('infoCCTypeId').selectedIndex].text + '<br/>';
    ccInfo += $('infoCCName').value + '<br/>';
    ccInfo += $('infoCCNumber').value + '<br/>';
    ccInfo += 'Expires: ' + $('infoCCExpMo').value + '/' + $('infoCCExpYear').value + '<br/>';
    ccInfo += 'Security code: ' + $('infoCCCode').value;
    $('reviewCC').update(ccInfo);
    
    if(objResponse.items && objResponse.items.length > 0){
        var cartDiv = new Element('div');	        	        
        var cartTotal = 0;
        var cartTotalPreDiscounts = 0;
        var cartTable = new Element('table');
        var cartTableBody = new Element('tbody');
        this._cartCourses = new Array();
        
        for(var x=0; x < objResponse.items.length; x++){
            var cartItem = objResponse.items[x];
            var cartTableRow = new Element('tr').addClassName('cart-item');
            var cartTableCellName = new Element('td');
            var cartTableCellPrice = new Element('td');

            cartTableCellName.appendChild(new Element('div').update(cartItem.Name));	            
            cartTableCellPrice.appendChild(new Element('div', {'class':'price'}).update(BEFormatCurrency(cartItem.TotalPrice)));

            cartTableRow.appendChild(cartTableCellName);
            cartTableRow.appendChild(cartTableCellPrice);	  
            cartTableBody.appendChild(cartTableRow);
            
            //increment our total in the cart
            cartTotal += cartItem.TotalPrice;
    
            //for transaction tracking        
            this._cartCourses.push({'Id':cartItem.Id, 'Name': cartItem.Name, 'Qty': cartItem.Qty, 'Price': cartItem.UnitPrice});
            this._cartTotal = cartTotal;
        }        
        
        cartTotalPreDiscounts = cartTotal;
        
        for(var x=0; x < objResponse.coupons.length; x++){
            var cartItem = objResponse.coupons[x];
            var cartTableRow = new Element('tr').addClassName('cart-item');
            var cartTableCellName = new Element('td');
            var cartTableCellPrice = new Element('td');
            var couponDiscount = (cartItem.TypeId == 1) ? cartItem.Total : cartTotalPreDiscounts / 100 * (cartItem.Total*100);

            cartTableCellName.appendChild(new Element('span').update(cartItem.Name + ' - '));
            cartTableCellName.appendChild(new Element('a', {'href':'#'}).update('Remove').observe('click', this.checkoutRemoveCoupon.bindAsEventListener(this, cartItem.Id)));         
            cartTableCellPrice.appendChild(new Element('div', {'class':'price'}).update(BEFormatCurrency(couponDiscount)));

            cartTableRow.appendChild(cartTableCellName);
            cartTableRow.appendChild(cartTableCellPrice);	  
            cartTableBody.appendChild(cartTableRow);
            
            //increment our total in the cart
            cartTotal -= couponDiscount;
            
            //for transaction tracking
            this._cartCourses.push({'Id':cartItem.Id, 'Name': cartItem.Name, 'Qty': 1, 'Price': couponDiscount});
            this._cartTotal = cartTotal;
        }	        
        
        //add the totals row
        var cartTotalRow = new Element('tr').addClassName('cart-total');
        var cartTotalCell1 = new Element('td', {'class':'total'}).update('Total');
        var cartTotalCell2 = new Element('td');
        var cartTotalDiv = new Element('div', {'class':'price'}).update('<strong>' + BEFormatCurrency(cartTotal) + '</strong>');
        cartTotalCell2.appendChild(cartTotalDiv);
        cartTotalRow.appendChild(cartTotalCell1);
        cartTotalRow.appendChild(cartTotalCell2);
        cartTableBody.appendChild(cartTotalRow);
                  
        cartTable.appendChild(cartTableBody);
        cartDiv.appendChild(cartTable);	        
        
        $('reviewCart').update();
        $('reviewCart').appendChild(cartDiv);
        $('checkoutInfo').hide();
        $('checkoutReview').show();
        
        //track goal review step
        be_globalSiteFramework.trackPageview('/courses/checkout/review');          
    }else{	    
        window.location = '/courses/';
    }  
};

beCoursesModule.prototype.checkoutReviewEdit = function(event){
    $('cart').show();
    $('checkoutInfo').show();
    $('checkoutReview').hide();
};

beCoursesModule.prototype.checkoutApplyCoupon = function(event){
    event.stop();
    if($('reviewCoupon').value.length > 0){
        this._transport.transmitRequest(this._channelId, 'validatecoupon', {couponCode:$('reviewCoupon').value}, this.checkoutApplyCouponCompleted.bindAsEventListener(this));        
    }
};

beCoursesModule.prototype.checkoutApplyCouponCompleted = function(objResponse){
    if(objResponse.result == 'ok'){
        $('reviewCouponError').hide();
        $('reviewCouponSuccess').show();
        this.checkoutReview(null);
    }else{
        $('reviewCouponSuccess').hide();
        $('reviewCouponError').update(objResponse.message);        
        $('reviewCouponError').show();
    }
};

beCoursesModule.prototype.checkoutRemoveCoupon = function(event, id){
    event.stop();
    $('reviewCouponError').hide();
    $('reviewCouponSuccess').hide();        
    this._transport.transmitRequest(this._channelId, 'removecoupon', {couponId:id}, this.checkoutRemoveCouponCompleted.bind(this));        
};

beCoursesModule.prototype.checkoutRemoveCouponCompleted = function(objResponse){
    this.checkoutReview(null);
};

beCoursesModule.prototype.checkoutFinalize = function(event){
    var stateRegion;
    if($('infoStateDiv').style.display != 'none'){
        stateRegion = $('infoState').value;
    }else{
        stateRegion = $('infoRegion').value;
    }

    var request = {
        firstname:$('infoFirstName').value,
        lastname:$('infoLastName').value,
        address1:$('infoAddress1').value,
        address2:$('infoAddress2').value,
        city:$('infoCity').value,
        state:stateRegion,
        zip:$('infoZip').value,
        country:$('infoCountry').value,
        cctypeid:$('infoCCTypeId').value,
        cctypename:$('infoCCTypeId')[$('infoCCTypeId').selectedIndex].text,
        ccname:$('infoCCName').value,
        ccnumber:$('infoCCNumber').value,
        ccexpmo:$('infoCCExpMo').value,
        ccexpyear:$('infoCCExpYear').value,
        cccode:$('infoCCCode').value
    };
    this._transport.transmitRequest(this._channelId, 'processorder', request, this.checkoutFinalizeCompleted.bind(this));        
};

beCoursesModule.prototype.checkoutFinalizeCompleted = function(objResponse){
    if(objResponse.result == 'ok'){
        $('checkoutReview').hide();
        $('checkoutCompleted').show();
        
        //track goal completed
        be_globalSiteFramework.trackPageview('/courses/checkout/completed');
        
        //build and submit full transaction
        var stateRegion = ($('infoStateDiv').style.display != 'none') ? $('infoState').value : stateRegion = $('infoRegion').value;
        
        var order = {
            orderId:objResponse.orderId,
            affiliation:'centralReach',
            total:this._cartTotal,
            tax:0,
            shipping:0,
            city:$('infoCity').value,
            state:stateRegion,
            country:$('infoCountry').value
        };
        
        var orderItems = new Array();
        
        for(var x=0; x < this._cartCourses.length; x++){
            orderItems.push({
                orderId:objResponse.orderId,
                sku:this._cartCourses[x].Id,
                name:this._cartCourses[x].Name,
                category:'Courses',
                price:this._cartCourses[x].Price,
                qty:this._cartCourses[x].Qty});
        }
        
        //submit full transaction
        be_globalSiteFramework.trackTransaction(order, orderItems);
        
    }else{
        $('reviewError').update(objResponse.message);
        $('reviewError').show();
    }
};
