﻿function configObj(c) {
	var o = { // Default Configuration
		urlListItems:'/OnDemand/ShoppingCart/ListItems',
		urlCheckout:'/OnDemand/Checkout/Index',
		urlRecordsPerPageList:'/OnDemand/Home/GetRecordsPerPageList',
		urlPurchaseableTraining:'/OnDemand/Home/GetPurchaseableTrainings/',
		urlFeatureTraining:'/OnDemand/Home/GetFeatureTrainings/',
		urlUpdateQuantity: '/OnDemand/ShoppingCart/UpdateQuantity',
		urlUpdateQuantityForCart: '/OnDemand/ShoppingCart/UpdateQuantityForEntireCart',
		urlAddToCart:'/OnDemand/ShoppingCart/AddMultipleItemsToCart',
		urlLoadCategoriesForOnDemand:'/Category/LoadCategoriesPagedForOnDemand',
		urlValidateUserDetails:'/Login/ValidateUserDetails',
		urlResetPassword:'/Login/ResetPassword',
		urlTypeList:'/Training/Directory/GetTypeList',
		urlHelp:'/content/helpsystem2/',
		
		locPageFormat:'Displaying {0}-{1} of {2}',
		locPageEmpty:'Displaying Nothing',
		locReplyTitle:'Title',
		locReplyIssue:'Issue',
		locTeplyError:'Error',
		locType:'Type',
		locTitle:'Title',
		locSeats:'Seats',
		locPrice:'Price',
		locEstTime:'Estimated Time',
		locSearch:'Search',
		locViewDetails:'View Details',
		locPreview:'Preview',
		locAddToCart: 'Add to Cart',
		locLanguage: 'Language',
		locCEU: 'CEU', 
		locCourse: 'Contains',
		locUpdatecartBtn: 'Update Cart',
		pageSize:10,
		lessonCode:'79',
		courseCode:'97',
		curriculumCode:'98',
		isOnDemand:true,
		isLoggedIn:false,
		showAllTraining:true,
		topLevelTrainingIDs:'79,97,98',
		trainingFilterTypes:'0',
		categoryIDs:'0',
		trainingTypeIDs:'0',
		companyName:'OnDemand',
		selectedNode:'AllTraining'
	}
	if (c) for (var n in c) o[n]=c[n];
	return o;
}
var opts = configObj(viewConfig);



/* ~~~~~~~~~~ MINI CART ~~~~~~~~~~ */

var itemStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: opts.urlListItems,
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
		{ root: 'Items' },
		[
			{ name: 'UniqueProductCode', mapping: 'UniqueProductCode' },
			{ name: 'Quantity', mapping: 'Quantity' },
			{ name: 'Title', mapping: 'Title' },
			{ name: 'Price', mapping: 'Price' },
			{ name: 'ItemPrice', mapping: 'ItemPrice' },
			{ name: 'DateAdded', mapping: 'DateAdded' },
			{ name: 'CEU', mapping: 'CEU' },
			{ name: 'Language', mapping: 'Language' }
		]
	),
    listeners:
		{ load: function(store, options) {
		    if (itemStore.getCount() == 0) {
		        document.getElementById('itemsHeading').style.display = "none";
		        document.getElementById('viewCartLink').style.display = "none";
		    }
		    else {
		        document.getElementById('viewCartLink').style.display = "inline-block";
		        document.getElementById('itemsHeading').style.display = "block";
		    }
		    var totalEl = document.getElementById('finalTotal');
		    var subtotalEl = document.getElementById('subTotal');
		    Ext.get([totalEl, subtotalEl]).animate({
		        color: { to: '#ff7777' }
		    },
            0.50,
            function() {


                Ext.get([totalEl, subtotalEl]).animate({
                    color: { to: '#000000' }
                },
                0.50,
                null,
                'easeOut',
                'color'
                );

            },
            'easeIn',
            'color'
            );
		}
		}
});

function ValdiateBeforeSubmit() {
	if(itemStore.getCount()==0) {
		Ext.Msg.alert('', 'Please add at least one Training to the Cart.');
		return false;
	}
	window.location.href = opts.urlCheckout;
}
function isDecimalNumber(e) {
    var keycode = (e.keyCode) ? e.keyCode : (e.which) ? e.which : (e.charCode) ? e.charCode : -1;
    if (Ext.isGecko) {
        if ((keycode >= 48 && keycode <= 57) || keycode == 8 || keycode == 9 || keycode == 37 || keycode == 39 || keycode == 46 || keycode == 35 || keycode == 36) {
            return true;
                    }

        else
            return false;
    }
    else
        if (Ext.isIE) {
        if ((keycode >= 48 && keycode <= 57) || keycode == 8) {          
            return true;
        }
        else
            return false;
    }
    return false;
}
function removeStoreLine(id) {
    store = itemGrid.getStore();
    record = store.getById(id);
    record.data.Quantity = 0;
    onItemUpdate(store, record, Ext.data.Record.EDIT)
}
function removeStoreLineForMiniCart(unicode) {
    store = itemGrid.getStore();
    row = store.find("UniqueProductCode", new RegExp('^' + Ext.escapeRe(unicode) + '$'));
    record = store.getAt(row);
    record.data.Quantity = 0;
    onItemUpdate(store, record, Ext.data.Record.EDIT)
}
function updateStore(target,unicode) {
 
    store = itemGrid.getStore();
    row = store.find("UniqueProductCode", new RegExp('^' + Ext.escapeRe(unicode) + '$'));
    record = store.getAt(row);  
    var initialSeats = record.get("Quantity");
    if (target.value == "")
        target.value = initialSeats;
    var regexp = /\d+/;
    if (regexp.test(target.value)) {
       
       

        var value = /(\d+)/i.exec(target.value);
        var seats = parseInt(value[1], 10);
        if (seats > 9999999)
            seats = parseInt(value[1].substring(0, 7));

        if (seats <= 9999999) {
            record.set("Quantity", seats);

        }
        else {
            Ext.Msg.alert('Invalid', 'The maximum allowed value is 9999999');
        }

    }
    else
        Ext.Msg.alert('Invalid', 'Seats should be numeric');
}

var itemColumnModel = new Ext.grid.ColumnModel([
	{
		id: 'Title',
		header: opts.locTitle,
		//width: 40,
		sortable: true,
		align:'left',
		dataIndex: 'Title'
	},{
		id: 'Quantity',
		header: opts.locSeats,
		width:67,
		sortable: true,
		align:'right',
		dataIndex: 'Quantity',
		renderer: function(value, meta, record, row, column, store) {
		return '<input id="ext-textrow-' + row + '" type="text"  value="' + value + '" onkeypress="return isDecimalNumber(event);" updateStore(this,{UniqueProductCode})  maxLength="7"style="margin:0px;width:51px;"/>';
		}  
		
	},{
		id: 'ItemPrice',
		header: opts.locPrice,
		width: 60,
		sortable: true,
		align: 'right',
		dataIndex: 'ItemPrice',
		renderer: function(value, meta, record, row, column, store) {
		return Ext.util.Format.usMoney(value) + '<div class="mini-store-remove"><a href="javascript:removeStoreLine(\'' + record.id + '\')">Remove</a></div>';
		}
	}
]);

		
	
// Updating quantity ////
var pbar1 = new Ext.ProgressBar({
	id: 'pbar1',
	width: 300
});
var loadingWin = new Ext.Window({
	title: 'Processing...',
	closable: false,
	border: false,
	modal: true,
	plain: false,
	width: 315,
	height: 50,
	items: [pbar1]
});
var updateQuantitySucceeded = function(response, record, quantity, price) {
  
    updateTotals(response);

    if (quantity == 0) {
        record.store.remove(record);
    } else {
        record.data['ItemPrice'] = (price * quantity);
        record.commit(false);
    }
    itemStore.load();
    loadingWin.hide();
};
        
var updateQuantityFailed = function(result, record) {
	loadingWin.hide();
	record.reject(false);
	Ext.Msg.alert('An error occurred while attempting to update the item quantity, please try the operation again or contact customer service for further assistance.');
};
function onItemUpdate(store, record, operation) {
	loadingWin.show();
	    pbar1.wait({
		interval: 500,
		duration: 500000,
		increment: 15
	});
	if (operation == Ext.data.Record.EDIT) {
		var uniqueProductCode = record.get('UniqueProductCode');
		var quantity = record.get('Quantity');
		var price = record.get('Price');
		var itemPrice = record.get('ItemPrice');
		if (itemPrice != (price * quantity)) {
			Ext.Ajax.request({
			   url: opts.urlUpdateQuantity,
			   success: function(response) { updateQuantitySucceeded(response, record, quantity, price); },
			   failure: function(response) { updateQuantityFailed(response, record); },
			   params: { uniqueProductCode: uniqueProductCode, quantity: quantity },
			   method: 'POST'
			});
		}
	}
};

var itemGrid = new Ext.DataView({
    renderTo: 'itemList',
    store: itemStore,
    autoScroll: true,
    loadingText: 'Loading',
    tpl: new Ext.XTemplate(
		'<tpl for=".">',
			'<span class="fieldRow">',
					'<div class="miniCartRow">',
					'<tpl><span class="miniCartTrainingTitleText">{Title}</span><br/><span class="miniCartNote">Seats:&nbsp;</span><span><input id="ext-row-{0}" type="text"  value={Quantity} onkeypress="return isDecimalNumber(event);" onblur="updateStore(this,\'{UniqueProductCode}\');" maxLength="7" style="margin:0px;width:20px;"/></span><span class="miniCartNote">&nbsp;&nbsp;Price:&nbsp;</span><span>{[fm.usMoney(values.ItemPrice)]}</span></tpl>&nbsp;&nbsp;&nbsp;', '<a href="javascript:removeStoreLineForMiniCart(\'{UniqueProductCode}\')"><span class="miniCartNote">Remove</span></a>',
					'<br/>', '</div>',
			'</span>',
		'</tpl>'
	),
    simpleSelect: true,
    itemSelector: 'span.tile',
    selectedClass: 'x-tile-selected',
    emptyText: '<div class="x-grid-empty">Your Shopping Cart is empty</div>',
   
     onUpdate : function(ds, record){
       
    }
});


var updateCartBtn = new Ext.Button({
    renderTo: 'updateCartBtn',
    text: opts.locUpdatecartBtn,
    tooltip: 'Update Cart',
    disabled: false,
    cls: 'x-apply'

});

updateCartBtn.on('click', function(button) {
     onItemUpdateForCart(itemGrid.getStore());
});


var onItemUpdateForCart = function(store, response) {
   
    loadingWin.show();
    pbar1.wait({
        interval: 500,
        duration: 500000,
        increment: 15
    });
    var productCodes = [];
    var quantity = [];
    var t = [];

    var list = store.getRange();
    for (var i = 0; i < list.length; i++) {
        productCodes.push(list[i].get('UniqueProductCode'));
        quantity.push(list[i].get('Quantity'));
        t.push(list[i].get('UniqueProductCode') + '-' + list[i].get('Quantity'));

    }
    var stringValue = t.join(',');

    Ext.Ajax.request({
        url: opts.urlUpdateQuantityForCart,
        success: function(response) { updateQuantitySucceededForCart(store, response); },
        failure: function(response) { updateQuantityFailedForCart(response, store); },
        params: { cartStringValue: stringValue },
        method: 'POST'
    });

};


var updateQuantitySucceededForCart = function(store, response) {

    updateTotals(response);

    var quantity = [];
    var price = [];
    var itemPrice = [];
    var list = store.getRange();
    var removeCounter = 0;
    for (var i = 0; i < list.length; i++) {
        itemPrice.push(list[i].get('ItemPrice'));
        quantity.push(list[i].get('Quantity'));
        price.push(list[i].get('Price'));

        if (quantity[i] == 0) {
            store.remove(store.getAt(removeCounter));
            removeCounter -= 1;
        }
        else
            store.getAt(removeCounter).data['ItemPrice'] = (price[i] * quantity[i]);

        removeCounter += 1;
    }
    store.commitChanges();
    loadingWin.hide();
    store.load();
};

var updateQuantityFailedForCart = function(result, store) {

    loadingWin.hide();
    store.rejectChanges(); ;
    Ext.Msg.alert('<%= Html.Resource("ExtErrorMsgUpdateItemQuantity") %>');
    
};

    
function limitText(limitField,limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} 
}





/* ~~~~~~~~~~ Paging Size Limit ~~~~~~~~~~ */

var gridRecordsStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
        url: '/OnDemand/Home/GetRecordsPerPageList',
        method: 'GET'
    }),
    reader: new Ext.data.JsonReader(
		{ root: 'ddlist' },
		[
			{ name: 'LookupCode', mapping: 'LookupCode' },
			{ name: 'LookupValueDesc', mapping: 'LookupValueDesc' }
		]
	),
    listeners:
	{ load: function(store, options) {
	        gridRecordsDD.setValue(464);
	    }
	}
});

var gridRecordsDD = new Ext.form.ComboBox({
	store: gridRecordsStore,
	displayField: 'LookupValueDesc',
	valueField: 'LookupCode',
	width: 50,
	typeAhead: false,
	editable:false,
	id:'recordsDD',
	triggerAction: 'all',
	selectOnFocus: true,
	lazyInit: false,
	forceSelection: true,
	mode: 'local'
});
     
          
function renderTitle(value, p, record) {
	var categories=[];
	var categoryTags=[];
	categories=record.get('AssociatedCategories');
	var categorytext='';
	if(categories.length>0)
	{
	for (i=0 ; i<categories.length; i++)
		   categoryTags.push("<a href=# onClick='loadTrainingStoreforSelectedCategory(" +categories[i].CategoryID +");'>" + categories[i].CategoryName + "</a>");
		   
	}  
	categorytext= categoryTags.join(", ");     
	return String.format('<div class="list-title">{0}</div><div class="list-description">{1}<br><br>Tags:{2}</div>', value, record.data.TrainingDesc,categorytext);
}
    
function convertTrainingTags(val, rec) {
	var categories=[];
	var categoryTags=[];
	categories=rec.CategoryEntities;//AssociatedCategories;
	var categorytext='';
	if (categories && categories.length > 0)
	{
		for (i=0 ; i<categories.length; i++)
			categoryTags.push("<a href=# onClick='loadTrainingStoreforSelectedCategory(" +categories[i].CategoryID +");'>" + categories[i].CategoryName + "</a>");
		categorytext= categoryTags.join(" ");
	}       
	return categorytext;
}
function convertCEUCredits(val, rec) {
    if (rec.CanDisplayPrintCEU) {
        var c = '.00';
        var start = "";
        var end = "";
        var str = start + val + end;
        var l = str.indexOf('.', 0);
        if (l == -1)
            return val + c;
        else
            return val;
    }
}

function convertCourse(val, rec) {
    var i;
    var k = "";
    var str = '<a href="/OnDemand/Home/Training/' + rec.TrainingID + '/' + rec.UrlName + '">View More</a>'
    if (val && val.length > 0) {
        for (i = 0; i < val.length && i < 6; i++) {
        if(i!=5)
            k = k + '<span class="details-lesson">' + val[i] + ' </span>';
          else
              k = k + '<span class="details-lesson">' + str+ ' </span>';
      }
      return k;
    }
} 

function indexOf(o, from) {
   var len = this.length;
   from = from || 0;
   from += (from < 0) ? len : 0;
   for (; from < len; ++from) {
      if (this[from] === o) {
           return from;
            }
        }
        return -1;
}

function renderImage(value, p, record) {            
	var cls = 'training-' + value;
	return '<div class="' + cls + '"><span class="icon"></span></div>';
}

function renderTime(value, p, record) {            
	return String.format('{0} min.', value);
}

var TrainingUnit = Ext.data.Record.create([
	'TrainingVersionID', 'Title', 'TrainingType', 'MinimumTime', 'EstimatedTime', 'TrainingDesc',
	'AssociatedCategories', 'RetailPricing', 'PreviewURL', 'ThumbnailURL', 'UniqueProductCode', { name: 'CEUCredits', convert: convertCEUCredits }, 'LanguageList',
	'CategoryEntities', { name: 'Tags', convert: convertTrainingTags }, 'IsPurchaseable', { name: 'ChildTitle', convert: convertCourse }, 'CanDisplayPrintCEU'
]);

var trainingStore = new Ext.data.JsonStore({
    url: '/OnDemand/Home/GetPurchaseableTrainings/',
    root: 'list',
    fields: TrainingUnit,
    idProperty: 'UniqueProductCode',
    totalProperty: 'totalCount',
    sortInfo: { field: "Title", direction: "ASC" },
    remoteSort: true,
    listeners: {
        beforeload: function(store, options) {
            var show = false;
            var SelfAssignOnly = !opts.showAllTraining;
            for (var i = 0; i < filterMenu.items.length; i++) {
                var selection = filterMenu.items.items[i];
                if (selection.id == "111" && selection.checked) {
                    show = true;
                }
            }

            if (options.params.trainingTypeIDs || options.params.categoryIDs) {
                store.baseParams.query = trainingSearchField.getValue();
                store.baseParams.trainingTypeIDs = (options.params.trainingTypeIDs == null) ? opts.trainingFilterTypes : options.params.trainingTypeIDs;
                store.baseParams.showAll = show;
                store.baseParams.showSelfAssignOnly = false;
                store.baseParams.categoryIDs = (options.params.categoryIDs == null) ? opts.categoryIDs : options.params.categoryIDs;
            } else {
                store.baseParams = {
                    query: trainingSearchField.getValue(),
                    trainingTypeIDs: opts.trainingFilterTypes,
                    showAll: show,
                    showSelfAssignOnly: false,
                    categoryIDs: opts.categoryIDs
                };
            }
        }
    }
});
    
function addToCartClickHandler()
{
        var recs = trainingGrid.getSelectionModel().getSelections();
		if (recs) addItemsToCart(recs);

}
var reformatMoneyAndRender = function(value, p, record) {
return '<span>' + Ext.util.Format.usMoney(value) + '</span>';
}

var reformatMoneyAndRenderForAddToCart = function(value, p, record) {
    return '<span class="item-Price"><span class="icon-small" style="padding-right:53px"><a href="#" class ="price" onclick="addToCartClickHandler();return false;">Add To Cart</a></span></span>';
}
        
function refreshTrainingGrid() {
    var show = false;
    pagingBar.pageSize = opts.pageSize;
    var showSelfAssign = false;
    for (var i = 0; i < filterMenu.items.length; i++) {
        var selection = filterMenu.items.items[i];
        if (selection.id == "111") {
            if (selection.checked) show = true;
        }
    }
    trainingGrid.getStore().load({ params: { start: 0, limit: opts.pageSize, showAll: show, showSelfAssignOnly: false} });
}

var pagingBar = new Ext.PagingToolbar({
	pageSize: opts.pageSize,
	store: trainingStore,
	displayInfo: false,
	autoScroll: true,
	displayMsg: opts.locPageFormat,
	emptyMsg: opts.locPageEmpty
});

gridRecordsDD.addListener('select', function(dd) {
    var pgSize = gridRecordsDD.getRawValue();
    if (pgSize != null && pgSize != '')
        opts.pageSize = parseInt(gridRecordsDD.getRawValue());
    else
        opts.pageSize = 10;
    refreshTrainingGrid();
});

var filterMenu = new Ext.menu.Menu({
	id: 'filterMenu',
	items: [{
		id: '000',
		text:'Select All',
		checked: true,
		checkHandler: onItemCheck,
		hideOnClick: false
	}]
});

filterMenu.on("hide", function(menu) {
	refreshTrainingGrid();
});
   
var trainingSearchField = new Ext.app.SearchField({
	store: trainingStore,
	width: 200,
	text: 'Search'
});

var viewBtn = new Ext.Action({
    text: 'View Details',
    //tooltip: opts.locViewDetails,
    disabled: true,
    iconCls: 'training-open',
    handler: function(btn) {

        var record = trainingGrid.getSelectionModel().getSelected();

        if (record && record.get("TrainingVersionID") >= 0) {

            loadTrainingDetails(record, btn.el);
        }
        if (tilePanel.getSelectionCount() == 1) {
      
            var tileRecord = tilePanel.getSelectedRecords()[0];
            loadTrainingDetails(tileRecord, btn.el);
        }

    }
});

var addToCartBtn = new Ext.Action({

    text: 'Add to Cart',
    //tooltip: opts.locAddToCart,
    disabled: true,
    iconCls: 'addtocart',
    handler: function() {
     
        var recs = trainingGrid.getSelectionModel().getSelections();
        if (recs) addItemsToCart(recs);

        if (tilePanel.getSelectionCount() > 0) {
            var tileRecords = tilePanel.getSelectedRecords();
            if (tileRecords) addItemsToCart(tileRecords);
        }
    }
});

function addToCartByID(id) {
	var rec = trainingStore.getById(id);
	if (rec) addItemsToCart([rec]);
}
function addItemsToCart(records) {
    if (!records || records.constructor != Array || records.length == 0) return;

	var uniqueProductCodes = "";
	for (var i = 0; i < records.length; i++) {
		if (uniqueProductCodes == "")
			uniqueProductCodes = records[i].get("UniqueProductCode");
		else
			uniqueProductCodes = uniqueProductCodes + ", " + records[i].get("UniqueProductCode");    
	}
	document.getElementById("hdnProductCodes").value = uniqueProductCodes;
	addToCartsave();   
}
function addItemToCartByProductCode(id) {
	
	if (!id) return;
	document.getElementById("hdnProductCodes").value = id;
	addToCartsave();
}

var addToCartform = new Ext.form.BasicForm('frmCart', {});
function addToCartsave() {
	addToCartform.submit({
		url: opts.urlAddToCart,
		method: 'Post',
		success: addToCartsaved,
		failure: addToCartsaved
	});
}
function addToCartsaved(form, action) {
   
	if (action.failureType) {
		var message = opts.locReplyTitle + '<br /><br />';
		if (action.result && action.result.errors) {
			message += '<b>' + locReplyIssue + '</b><ul>';
			message += '<li>' + action.result.errors + '</li>';
			message += '</ul>';
		}
		Ext.Msg.alert(locTeplyError, message);
	} else {
		updateTotals(action.response);
		itemStore.load();                  
	}
}

var updateTotals = function(response) {

    var result = Ext.decode(response.responseText);
    var removedDiscounts = result.removedDiscounts

    if (removedDiscounts.length > 0) {
        var message = '<br>';
        message += '<b>Issue</b><ul>';
        for (var i = 0; i < removedDiscounts.length; i++) {
            if (removedDiscounts[i])
                message += '<li>' + removedDiscounts[i] + '</li>';
        }
        message += '</ul>';
        Ext.Msg.alert('Removed Promo Codes', message);
    }

    var totalEl = document.getElementById('subTotal');
    var finalTotalEl = document.getElementById('finalTotal');
    var discount = document.getElementById('discount');

    if (!opts.isLoggedIn && totalEl) {
        totalEl.innerHTML = Ext.util.Format.usMoney(result.subTotal);
        finalTotalEl.innerHTML = Ext.util.Format.usMoney(result.total);
        discount.innerHTML = Ext.util.Format.usMoney(result.discount);
    }
    else if (opts.isLoggedIn && totalEl) {
        totalEl.innerHTML = Ext.util.Format.usMoney(result.subTotal);
        finalTotalEl.innerHTML = Ext.util.Format.usMoney(result.total);
        discount.innerHTML = Ext.util.Format.usMoney(result.discount);
    }
    document.getElementById('hdnActualTotal').value = result.total;
    document.getElementById('hdnSubTotal').value = result.subTotal;
};




/* ~~~~~~~~~~ Training Types ~~~~~~~~~~ */

var trainingTypeStore = new Ext.data.JsonStore({
	url: '/Training/Directory/GetTypeList',
	root: 'ddlist',
	fields: ['LookupCode', 'LookupValueDesc'],
	listeners: {
		load: function(store, records, options) {
			if (records.length > 0) {
				filterMenu.addItem(new Ext.menu.Separator());
				for (var i = 0; i < records.length; i++) {
					var code = records[i].get('LookupCode');
					var checked = (code == opts.lessonCode || code == opts.courseCode || code == opts.curriculumCode );

					filterMenu.addItem(new Ext.menu.CheckItem({
						id: code,
						text: records[i].get('LookupValueDesc'),
						checked: true,
						checkHandler: onItemCheck,
						hideOnClick: false
					}));
				}
				onItemCheck(null, false);
			}
		}
	}
});






/* ~~~~~~~~~~ Training Lists ~~~~~~~~~~ */

var trainingGrid = new Ext.grid.GridPanel({
	cm: new Ext.grid.ColumnModel([
		{ header: opts.locType, sortable: true, width: 50, dataIndex: 'TrainingType', align: 'right', renderer: renderImage },
		{ id:'trainingTitle', header: opts.locTitle, sortable: true, hideable: false, dataIndex: 'Title'},
		{ header: 'Language', sortable: true, width: 60, dataIndex: 'LanguageList'},
		{ header: opts.locEstTime, sortable: true, width: 100, dataIndex: 'EstimatedTime', renderer: renderTime },
		{ header: 'Price Per Seat', sortable: true, width: 80, dataIndex: 'RetailPricing', renderer: reformatMoneyAndRender },
		{ header: 'Add To Cart', width: 100, renderer: reformatMoneyAndRenderForAddToCart },
		{ header: 'Contains', sortable: true, width: 60, dataIndex: 'ChildTitle' }
	]),
	boxMinWidth: 140,
	autoExpandColumn: 'trainingTitle',
	height: 445,
	store: trainingStore,
	enableDragDrop: true,
	border:false,
	ddGroup: 'childTree',
	region:'center',
	loadMask: true,
	autoScroll: true,
	listeners: {
		rowdblclick: function(grid, rowIndex, e) {
			var record = grid.getStore().getAt(rowIndex);
			if (record) loadTrainingDetails(record, e.target);
		}
	}
});

function onItemCheck(item, checked) {
	var arrayIDs = [];
	for (var i = 0; i < filterMenu.items.length; i++) {
		var selection = filterMenu.items.items[i];
		if (item != null) 
		{
			if (item.id == '000') {
				if (selection.ctype == 'Ext.menu.CheckItem' && selection.id != '111' && selection.id != '222' && selection.id != '333') {
					if (checked) {
						selection.setChecked(true, true);
					} else {
						selection.setChecked(false, true);
					}
				}
			}
		   
			else if (item.id > 0) {
				if (selection.id == '000') {
					if (!checked) {
						selection.setChecked(false, true);
					}
				}
			}
		}
	   
		if (selection.id != '000' && selection.checked != null && selection.checked && !selection.hidden)
			arrayIDs.push(selection.id);
	}

	var filterTypeIDs = '';

	if (arrayIDs.length > 0) {
		filterTypeIDs = arrayIDs.join(',');
	}

	if (filterTypeIDs == '')
		filterTypeIDs = '0';

	opts.trainingFilterTypes = filterTypeIDs;           
	
}
	
function renderLinks(value, p, r) {
	return String.format('<a href="/Assignment/Directory/Open/{1}" class="assignment-title">{0}</a>', value, r.get('AssignmentMasterID'));
}

function convertDate(val, rec) {
	return val ? new Date(Number(val.match(/\d+/))) : null;
}

function displayDate(data) {
	return data ? (data.getMonth() + 1) + "/" + data.getDate() + "/" + data.getFullYear() : "<em>(No Date)</em>";
}     

function renderDesc(value, p, record) {
	return String.format('<div class="list-title"><span class="icon">{0}</span></div>', value);
}

function renderDefault(value, p, record) {
	if (value == true)
		return 'Default';
	else
		return 'Custom';
}

/* ~~~~~~~~~~ Layout ~~~~~~~~~~ */ 

var ChildNode = Ext.extend(Ext.tree.AsyncTreeNode, {});

var  allTrainingNode= new Ext.tree.AsyncTreeNode({text: '<span title=\"Displays all training in the library\" ><font size=2>All Training</font></span>',
	id: '1',
	idValue: 0,
	cls :'node-spacing',
	icon: '/Content/Skin/Shared/world.png',
	leaf : true,
	type : 'Training'
}); 

var rootNode = new Ext.tree.TreeNode({
	text: 'Directory Root',
	type:'root'
});
rootNode.appendChild(allTrainingNode);


var rootNodeChildrenStore = new Ext.data.JsonStore({
    proxy: new Ext.data.HttpProxy({
        url: '/Training/Directory/GetLibraryTreeNodesForOnDemandHome',
        method: 'GET'
    }),

    root: 'list',
    fields: [
		 'text', 'CategoryName', 'idValue', 'type'

	],
    listeners: {
        load: function(store) {
            var treeNodes = [];
            var list = store.getRange();
            for (var i = 0; i < list.length; i++) {
                var newNode = new Ext.tree.AsyncTreeNode({ text: list[i].get('text'),
                    idValue: list[i].get('idValue'),
                    icon: '/Content/Skin/Shared/tag_blue.png',
                    cls: 'node-spacing',
                    leaf: true,
                    type: 'Category'
                });
                treeNodes.push(newNode);
            }
            if (treeNodes.length) rootNode.appendChild(treeNodes);

            if (rootNode.findChild("idValue", opts.categoryIDs))
                rootNode.findChild("idValue", opts.categoryIDs).select();
            else
                allTrainingNode.select();
        }
    }

});
     
var libraryTree = new Ext.tree.TreePanel({
    tbar : new Ext.Toolbar({ height : 28 }),
	region: 'west',
	split: true,
	height: 445,
	minSize: 180,
	id: 'libraryTree',                       
	width: 180, 
	collapsible: false,
	rootVisible: false,
	autoScroll: true,
	useArrows: true,
	animate: false,
	containerScroll: true,
	enableDrag: false,
	enableDrop: false,
	dropConfig: {
		allowParentInsert:false
	},
	root: rootNode
});




libraryTree.getSelectionModel().on("selectionchange", function(selectModel, newNode, oldNode) {
	if(newNode) {
        if(newNode.id == '1') {  
			resetFilter();
			trainingSearchField.setValue('');
			opts.categoryIDs="0";
		} else if (newNode.attributes.type=="Category" && newNode.attributes.idValue > 0) {        
			resetFilter();
			trainingSearchField.setValue('');
			trainingStore.setDefaultSort("Title","ASC");
			opts.categoryIDs = newNode.attributes.idValue;
		}
		trainingGrid.getStore().load({params:{start:0,limit:opts.pageSize, trainingTypeIDs:opts.trainingTypeIDs,categoryIDs:opts.categoryIDs}});
	}  
});


function loadTrainingStoreforSelectedCategory(categoryID) {
	if (detailsWin) detailsWin.hide();
	resetFilter();
	trainingStore.setDefaultSort("Title","ASC");
	opts.categoryIDs = categoryID;
	if(rootNode.isExpanded())
		libraryTree.selModel.select(rootNode.findChild("idValue",categoryID));
}
     
function resetFilter() {
	var items = filterMenu.items.items;
	for (var i = 0; i < items.length; i++)  {
		if (items[i].ctype == 'Ext.menu.CheckItem') {  
			items[i].setChecked((items[i].id != '111' && items[i].id != '222'), true);
			items[i].setVisible(true);  
		}             
	}
	opts.trainingFilterTypes = opts.trainingTypeIDs; // all types       
}
var tilePanel = new Ext.DataView({
   // boxMinWidth: 140,
	multiSelect:true,
	store:trainingStore,
	autoScroll:true,
	loadingText:'Loading',
	tpl:new Ext.XTemplate(
		'<tpl for=".">',
			'<span class="tile training-unit">',
				'<div class="tile-wrap">',
					'<div class="thumb-wrap"><div class="thumb">',
						'<tpl if="ThumbnailURL"><img src="{ThumbnailURL}" title="{Title}" /></tpl>',
						'<tpl if="!ThumbnailURL"><img src="/Content/Skin/Shared/s.gif" class="tile-missing" title="{Title}" /></tpl>',
					'</div></div>',
					'<div class="note-wrap">',
						'<a href="#" onclick="loadTrainingDetails(\'{UniqueProductCode}\',this);return false;" class="title" title="View Details">{Title}</a>',
							'<span class="item-Price"><span class="note">price per seat:</span> {[fm.usMoney(values.RetailPricing)]}</span><br/>',
							'<a href="#" class="price"  onclick="addToCartByID(\'{UniqueProductCode}\');return false;" title="Add To Cart">',
							'<img src="/Content/Skin/Shared/images/cart_add.png"/>&nbsp;Add To Cart</a>',
					'</div>',
				'</div>',
			'</span>',
		'</tpl>'
	),
	simpleSelect:false,
	itemSelector:'span.tile',
	selectedClass:'x-tile-selected',
	emptyText:'<div class="x-grid-empty">No Training Units Available</div>'
});

var centerPanel = new Ext.Panel({
    items: [tilePanel, trainingGrid],
    border: true,
    layout: 'card',
    activeItem: 0,
    //boxMinWidth: 140,
    region: 'center',
    tbar: [
		viewBtn,
		addToCartBtn,
		'-',
		new Ext.Toolbar.SplitButton({
		    text: 'View',
		    handler: function(btn) {
		        
		        var toGrid = centerPanel.getLayout().activeItem == tilePanel;
		        btn.menu.items.itemAt(0).setChecked(!toGrid);
		        btn.menu.items.itemAt(1).setChecked(toGrid);
		    },
		    menu: { items: [
				{ text: 'Thumbnails',
				    checked: true,
				    group: 'view',
				    checkHandler: function() { centerPanel.getLayout().setActiveItem(tilePanel); trainingGrid.getSelectionModel().clearSelections(); }
				}, {
				    text: 'List',
				    checked: false,
				    group: 'view',
				    checkHandler: function() {
				        centerPanel.getLayout().setActiveItem(trainingGrid);
				        tilePanel.clearSelections();
				    }
				}
			]
		    }
		}),
		'->','Search:&nbsp;',
		trainingSearchField
	],
    bbar: [pagingBar, '->', gridRecordsDD, { xtype: 'tbtext', text: 'Items per page'}]
});

var libraryPanel = new Ext.Panel({
	items: [libraryTree,centerPanel], 
	border: false,
	layout: 'border',
	height: 445,
	autoScroll: true,
	applyTo: 'onDemandGrid'
});

function resize() {
    centerPanel.doLayout();
    libraryPanel.doLayout();
}

Ext.EventManager.onWindowResize(resize);
//Details Window
 var trainingDetailTemplate = new Ext.XTemplate(
	'<tpl if="PreviewURL"><img id="tdScreenShot" src="{PreviewURL}" alt="{Title}" /></tpl>',

	'<div class="unit-props">',
	'<h3 class="unit-title">{Title}</h3>',
		'<tpl if="values.UniqueProductCode">',
			'<span class="unit-price"><span class="price">{[fm.usMoney(values.RetailPricing)]}</span> ',
				'<span class="note">per seat<cite title="A seat is one person taking training.">*</cite></span>',
			'</span>',
		'</tpl>',
		'<tpl if="values.LanguageList"><span class="details-language" title="' + opts.locLanguage + '" > ' + opts.locLanguage + ': {LanguageList}</span></tpl>',
		'<tpl if="values.EstimatedTime"><span class="details-time" title="' + opts.locEstTime + '"> '+ opts.locEstTime +': {EstimatedTime} min</span></tpl>',
		'<tpl if="values.CEUCredits"><span class="details-CEU" title="' + opts.locCEU + '">' + opts.locCEU + ': {CEUCredits}</span></tpl>',
		'<tpl if="values.Tags"><span class="details-tags" title="Category Tags">{Tags}</span></tpl>',
		'<tpl if="values.ChildTitle"><span class="details-course" title="' + opts.locCourse + '">' + opts.locCourse + ': </span>{ChildTitle}</tpl>',
	'</div>',
	'<div class="unit-desc">{TrainingDesc}</div>'
);

 var detailsWin = new Ext.Window({
 	title: opts.locPreview,
 	tpl: trainingDetailTemplate,
 	closeAction: 'hide',
 	closable: true,
 	border: false,
 	modal: true,
 	plain: true,
 	width: 700,
 	height: 400,
 	autoScroll: true,
 	showRecord: function(record, tar) {
 		detailsWin.record = record;
 		var canBuy = record.data.UniqueProductCode != null;
 		detailsWin.btnAddToCart.setVisible(canBuy);
 		if (detailsWin.buttons[0])  detailsWin.buttons[0].setVisible(canBuy)
 		detailsWin.show(tar);
 	},
 	listeners: {
 		beforeshow: function() {
 			if (detailsWin.record) detailsWin.update(detailsWin.record.data);
 		}
 	},
 	buttonAlign: 'left',
 	fbar: [
		'<span class="note">*A seat is one person taking training.</span>', '->',
		{ text: 'Add To Cart',
			ref: '../btnAddToCart',
			handler: function(btn) {
				addItemsToCart([detailsWin.record]);
				detailsWin.hide();
			}
		}, { text: 'Close',
			handler: function(btn) {
				detailsWin.hide();
			}
		}
	]
 });

function loadTrainingDetails(record, el) {
	if (typeof record == 'string') record = trainingStore.getById(record);
	if (record && record.constructor != TrainingUnit) return;
	detailsWin.showRecord(record, el); 
}

tilePanel.on("selectionchange", function(dataView, selections) {
    if (selections.length == 0) 
        addToCartBtn.disable();
    else
        addToCartBtn.enable();    
        
    if (selections.length == 1)
        viewBtn.enable();   
    else
        viewBtn.disable(); 
});


trainingGrid.getSelectionModel().on("rowselect", function(model, rowIndex, record) {
	var list = trainingGrid.getSelectionModel().getSelections();
	var selectCount = trainingGrid.getSelectionModel().getCount();
	if(selectCount > 0)
	{
		var enable = true;
		for(var i = 0; i< selectCount ; i++) {
			if(list[i].data.IsPurchaseable != true)
				enable = false ;
		}
		if(enable)
		{
			addToCartBtn.enable();
		}
		else
		{
		   addToCartBtn.disable();
		}
	}
	if (selectCount == 1) {
		viewBtn.enable();
	} else {
		viewBtn.disable();
	}
});

trainingGrid.getSelectionModel().on("rowdeselect", function(model, rowIndex, record) {
	var list = trainingGrid.getSelectionModel().getSelections();
	if (list.length == 0) {viewBtn.disable(); addToCartBtn.disable();}
	var selectCount = trainingGrid.getSelectionModel().getCount();
	if (selectCount == 1) {
		viewBtn.enable();
	} else {
		viewBtn.disable();
	}
	if(selectCount > 0)
	{
		var enable = true;
		for(var i = 0; i< selectCount ; i++)
		{
			if(list[i].data.IsPurchaseable != true)
				enable = false ;
		}
		if(enable)
		{
			addToCartBtn.enable();
		}
		else
		{
		   addToCartBtn.disable();
		}
	}
	
});

/////Mini Cart ///

var reformatMoney = function(id) {
 
	var el = document.getElementById(id);
	el.innerHTML = Ext.util.Format.usMoney(el.innerHTML);
}
var purchaseBtn = new Ext.Button({
    cls: 'flow-next',
	iconCls: 'training-purchase',
	//cls:'x-apply',
	text: 'Checkout',            
   // renderTo:'purchaseBtn',
	handler: function(btn) {
	if (opts.isLoggedIn) {
	  ValdiateBeforeSubmit();
	 }
	 else
	 {            
	   
	   if( itemStore.getCount()==0)
		{
		Ext.Msg.alert('', 'Please add at least one Training to the Cart.');
	   
		}
		else
		   window.location.href = '/Ondemand/Home/Login/?returnTo=/OnDemand/Checkout';
	 }
	
	  
}});

Ext.ns('Ext.ux');
Ext.ux.SideTabs = Ext.extend(Ext.BoxComponent, {
	
	selectedCls: 'x-selected',
	cls:'x-sidetab',
	
	initComponent : function() {
		
		this.tpl = new Ext.XTemplate(
			'<span class="x-sidetab-nav">',
				'<tpl for="sections">',
					'<div id="{[this.id]}-nav-item-{[xindex-1]}" class="x-sidetab-nav-item {headCls} {cls}" title="{title}">{head}</div>',
				'</tpl>',
			'</span>',
			'<span class="x-sidetab-body">',
				'<tpl for="sections">',
					'<div id="{[this.id]}-body-item-{[xindex-1]}" class="x-sidetab-body-item {bodyCls} {cls}">{body}</div>',
				'</tpl>',
			'</span>',
			{
				id:this.id
			}
		);
		
		Ext.ux.SideTabs.superclass.initComponent.call(this);
	},
	
	afterRender : function(){
		Ext.ux.SideTabs.superclass.afterRender.call(this);
		
		this.mon(this.el, {
            "click": this.onClick,
            scope:this
        });
		
		if (isNaN(this.selectedIndex)) {
			this.selectedIndex = 0;
		}
		this.updateDisplay();
	},
	
	onClick : function(e, el){
		var tar = Ext.get(el),
			head = tar.hasClass('x-sidetab-nav-item')? tar: tar.parent('.x-sidetab-nav-item');
		if (!head) return;
		this.selectIndex(head.id.match(/-nav-item-(\d+)/)[1] || 0);
	},
	selectIndex : function(idx) {
		if (!isNaN(idx) && this.selectedIndex != idx) {
			this.selectedIndex = idx;
			this.updateDisplay();
		}
	},
	
	onResize : function() {
		Ext.ux.SideTabs.superclass.onResize.apply(this, arguments);
		this.updateSize();
	},
	updateSize : function() {
		var w = this.getWidth();
		var el = Ext.select('.x-sidetab-nav', true, this.el.dom).elements[0];
		w -= el.getWidth();
		el = Ext.select('.x-sidetab-body', true, this.el.dom);
		el.setWidth(w);
	},
	updateDisplay : function() {
		if (!this.rendered) return;
		Ext.select('.x-sidetab-nav-item', false, this.el.dom).each(this.updateHeadItem, this);
		Ext.select('.x-sidetab-body-item', false, this.el.dom).each(this.updateItemDisplay, this);
		this.updateSize();
	},
	updateHeadItem : function(item, all, idx) {
		if (this.selectedIndex != idx) {
			item.removeClass(this.selectedCls);
		} else if (!item.hasClass(this.selectedCls)) {
			item.addClass(this.selectedCls);
		}
	},
	updateItemDisplay : function(item, all, idx) {
		item.setStyle({ display: this.selectedIndex == idx? '':'none' });
	}
	
	
});


function bindHelp() {
	var aHelp = Ext.select('.login-help a.help');
	var aTutor = Ext.select('.login-help a.tutorial');
	if (!aHelp || !aTutor) return;
	
	var helpUrl = opts.urlHelp;
	if (helpUrl.charAt(helpUrl.length-1) == "/") {
		helpUrl = helpUrl.slice(0, -1);
	}
	
	var helpTabs = new Ext.ux.SideTabs({
		data:{
			sections:[
				{	title:'Topics',
					headCls:'tab-help-topics',
					head:'<span></span>',
					bodyCls: 'tab-body',
					body:	'<h3>Help Topics</h3><p>How can we redirect your call?</p>' +
							'<ul>' + 
								'<li><em>Quick Start Guide</em> for <a href="' + helpUrl + '/ondemandqsgindividualaccounts.pdf" target="_blank">an Individual</a> or <a href="' + helpUrl + '/ondemandqsgbusinessaccounts.pdf" target="_blank">a Business</a></li>' + 
								'<li><a href="javascript:PS.view.helpWin.showTutorial();">Video Tutorial</a></li>' + 
								'<li><a href="' + helpUrl + '" target="_blank">Online Help</a> (<a href="' + helpUrl + '/ondemandguide.pdf" target="_blank">Download as PDF</a>)</li>' + 
								'<li><a href="' + helpUrl + '?frequentlyaskedquestions.htm" target="_blank">Frequently Asked Questions (FAQ)</a></li>' + 
							'</ul>' + 
							'<p>Coming from the old On Demand</p>' + 
							'<ul>' + 
								'<li><a href="' + helpUrl + '?whatsnewinondemand.htm" target="_blank">New Features</a></li>' + 
								'<li><a href="http://info.puresafety.com/OnDemandFAQs.html" target="_blank">Migration FAQ</a></li>' + 
							'</ul>'
				},
				{	title:'Tutorial',
					headCls:'tab-help-tutorial',
					head:'<span></span>',
					body:	'<object width="100%" height="100%">' + 
								'<param name="movie" value="/Content/Movie/OnDemandVideo.swf">' + 
								'<param name="base" value="/Content/Movie/">' + 
								'<embed src="/Content/Movie/OnDemandVideo.swf" base="/Content/Movie/" width="750" height="500">' + 
							'</embed>'
				}
			]
		}
	});
	
	var helpWin = new Ext.Window({
		width:834,
		height:535,
		closeAction:'hide',
		layout:'fit',
		title:'Help',
		modal:true,
		items:[ helpTabs ],
		showTutorial : function() {
			helpTabs.selectIndex(1);
		}
	});
	
	Ext.ns('PS.view');
	PS.view.helpWin = helpWin;
	
	aHelp.on('click', function(e){
		e = e || window.event;
		helpTabs.selectIndex(0);
		helpWin.show(e.target);
		if (e.preventDefault) e.preventDefault();
		return false;
	});
	aTutor.on('click', function(e){
		e = e || window.event;
		helpTabs.selectIndex(1);
		helpWin.show(e.target);
		if (e.preventDefault) e.preventDefault();
		return false;
	});
}

////MINI Cart ///////////
Ext.onReady(function() {
  
    trainingTypeStore.load();
    gridRecordsStore.load();
    itemStore.load();
    reformatMoney('subTotal');
    reformatMoney('discount');
    reformatMoney('finalTotal');
    rootNodeChildrenStore.load();
    purchaseBtn.render('purchaseBtn');
    bindHelp();
    
});


