
// Business Catalyst Function Overrides and Formatting Extensions
jQuery(function($) {

	var shadeFund = {
		overrides : {
			
					addToCart : function() {
					
							shadeFund.formatting.homeCycle();
							shadeFund.formatting.listpreviews();						
							shadeFund.formatting.checkouttemplate();
							shadeFund.formatting.activenav();
							shadeFund.formatting.alterNameDisplay();					
							shadeFund.formatting.entrepreneurTemplates();				
							shadeFund.formatting.partnerTemplate();
							shadeFund.formatting.teamholdererror();
							shadeFund.formatting.teamloginsignup();
							shadeFund.formatting.teamsecure();
							shadeFund.formatting.startTeam();
							shadeFund.formatting.secureZonePosts();
							shadeFund.formatting.supportbaskettemplate();					
							shadeFund.formatting.supportPortfolio();
							shadeFund.formatting.shoppingCartLanguage();							
							shadeFund.formatting.productQuantity();			
							shadeFund.formatting.priceInputCleanUp();				
	
						
						if (typeof AddToCart !== 'function') { return; }      
						var fnc = AddToCart;        
						AddToCart = function(){
							fnc.apply(this,arguments);
							shadeFund.formatting.homeCycle();
							shadeFund.formatting.listpreviews();						
							shadeFund.formatting.checkouttemplate();
							shadeFund.formatting.activenav();
							shadeFund.formatting.alterNameDisplay();					
							shadeFund.formatting.entrepreneurTemplates();				
							shadeFund.formatting.partnerTemplate();
							shadeFund.formatting.teamholdererror();
							shadeFund.formatting.teamloginsignup();
							shadeFund.formatting.teamsecure();
							shadeFund.formatting.startTeam();
							shadeFund.formatting.secureZonePosts();
							shadeFund.formatting.supportbaskettemplate();					
							shadeFund.formatting.supportPortfolio();
							shadeFund.formatting.shoppingCartLanguage();							
							shadeFund.formatting.productQuantity();			
							shadeFund.formatting.priceInputCleanUp();										
							//window.alert = _alert;
						};
					},
					updateItemQuantity : function() {
						if (typeof UpdateItemQuantity !== 'function') { return; }  
						
						var fnc = UpdateItemQuantity;
						UpdateItemQuantity = function() {
							//window.alert = function(msg){};
							fnc.apply(this,arguments);

							shadeFund.formatting.alterNameDisplay();
							shadeFund.formatting.supportbaskettemplate();
							shadeFund.formatting.priceInputCleanUp();							
							//window.location.reload()
						}
					}				
	
		},
		formatting : {
							////////////////////////////////////team functions////////////////////////////////////
							
							//keep at top
							//team secure pages
							teamsecure : function() {
								if ($('body#teamsecure')[0]) {
									
									//remove left side team facts that don't match teamholder
									function eachleftcolumn (teamholderLC) {
										$('div#leftside > div').each(function() {
											if ($(this).attr('class') == teamholderLC) {
												//get team name from leftside and apply
												var teamName = $(this).attr('id').split('~')[1];
												$(this).css('visibility','visible');
												$('div#titlebar h1').text(teamName);
												$('table.forum td.name a').text(teamName);
												$('div#maincontenthold h3.title').text(teamName);

												
											} 
											else if ($(this).attr('class') !== teamholderLC) {
												$(this).remove();
											}  							
										});	
									}
									//append forum links with team holder
									function appendforumlinks (teamholder) {
										if ($('table.topic a')[0]) {
											$('table.topic a').each(function() {
												var linkPath = $(this).attr('href');
												$(this).attr('href', linkPath + "&teamholder=" + teamholder);
											});
										}
										if ($('div.forum-posts-container')[0]) {
											var linkPath = $('div.forum-posts-container h3 a').attr('href');
											$('div.forum-posts-container h3 a').attr('href', linkPath + "&teamholder=" + teamholder);
										}
									}							
									//append form actions based on teamholder
									function appendFormActions (teamholder) {
											//form send to friend
											if ($('div.spreadword form')[0]) {
												var actionString = $('div.spreadword form').attr('action');
												var appendedPath = "&PageID=/support-teams/" + teamholder +"/"
												$('div.spreadword form').attr('action',actionString + appendedPath);
											}
											//update account - first string value requires questionmark
											if ($('div.accountpreferences form')[0]) {
												//form update account
												var actionString = $('div.accountpreferences form').attr('action');
												var appendedPath = "?PageID=/support-teams/" + teamholder +"/"
												$('div.accountpreferences form').attr('action',actionString + appendedPath);
											}
											// populate hidden email form with team name
											$("table.webform tr input.teamname").val(teamholder);
									}
									//check title if it starts with team and functions
									if ((document.title.split('-')[0] == "Team") && ($.url.param("ForumID") == null)) {
									
										var teamholder = document.title
										//pass title val to eachleftcolumn function
										eachleftcolumn (teamholder);
										//append forum link with team holder - only one on team page
										var linkPath = $('table.forum td.name a').attr('href');
										$('table.forum td.name a').attr('href', linkPath + "&teamholder=" + teamholder);
										//append form actions with teamholder								
										appendFormActions (teamholder);
									} 
									//forum pages and functions
									else if (($.url.param("ForumID") !== null) && ($.url.param("teamholder") !== null))  {
									// associate team with forum elements of page
										var teamholder = $.url.param("teamholder");
										//pass title val to eachleftcolumn function
										eachleftcolumn (teamholder);
										// append forum links to pass teamholder
										appendforumlinks (teamholder);
										//append form actions with teamholder
										appendFormActions (teamholder);
		
									 }
									//check if facebook is there and place above spread the word
									if ($('div.facebook').attr('id').length != 0) {					
										$('div.spreadword').before($('div.facebook').html());
									}
									
									
									
								}
							},
							//secure suggest a team form
							startTeam : function() {
								if ($('body#team form#startTeam')[0]) {
										$('input.teamName').blur(function() {
											//build the date add zero to single digit days and months for listing order
											var d = new Date();						
											if (d.getMonth()+1 < 10) {
												var month = "0" + (d.getMonth()+1);
											}
											else {
												var month = d.getMonth()+1;
											}
											if (d.getDate() < 10) {
												var day = "0" + d.getDate();
											}
											else {
												var day = d.getDate();
											}
											var dateEntered = d.getFullYear() + "-" + month + "-" + day;
											var	postTitle = $('input.teamName').val();
											//add elements together to build the itemName for admin
											$('input#ItemName').val(dateEntered+"~"+postTitle);
										});						
								}
							},
							//use by team list and detail layouts to remove links to login and join if no holder is applied
							teamholdererror : function() {
								if ($('body#team')[0]) {
									$('div#loginjoin').each(function() {
										if ($(this).attr('class') =="None") {
											$(this).remove();
										}
									});
								}
							},
							//team login and signup pages - present the right team form and team name from url
							teamloginsignup : function() {
								if ($('body#team.login')[0] || ($('body#team.signup')[0])) {
									var currentTitle = $('div#titlebar h1').text();
									var currentTeamSelect = "div." + $.url.param("team");
									var splitTeamName = $.url.param("teamName").split('~')[1];
									$('div#titlebar h1').text(currentTitle + " - " + splitTeamName);
									$(currentTeamSelect).css('display','block');
									
								}
							},
							////////////////////////////////////end team functions////////////////////////////////////					
							//homeCycle
							homeCycle : function() {
								if ($('body#home')[0]) {
									$('#pix').cycle({pager: 'div.nav', fx: 'fade', pause: 1, delay:6000 , timeout:6000 , speed:  1000});		
								}
							},
							//edit remove num and tilda from names
							alterNameDisplay : function() {
								//function to split and return second item in array
								function splitter(itemName, splitWith) {
									var splitData1 = itemName.split(splitWith)[1];
									return splitData1;
								}
								// pass text and split with to splitter return second item and replace text
								$('td.firstrow div.productitemcell a, title, h1, span.productName, p strong a, p a, div.pages-content p, div.pages-content h5, div.ephold p strong, li.zoneName a').each(function() {
									var splitDataVal = splitter($(this).text(), "~")
									if (splitDataVal) {
										$(this).text(splitDataVal);
									}
								});
							},
							// add selected to nav based on body
							activenav : function() {
								var bodysID = $('body').attr('id');
								$("ul#nav_787316 li").each(function() {
									if (bodysID == "entrepreneur") {
										$('ul#nav_787316 li.entrepreneurs').addClass("selected");
									} 
									else if (bodysID == "about") {
										$('ul#nav_787316 li.about-shadefund').addClass("selected");
									}
									else if (bodysID == "partner") {
										$('ul#nav_787316 li.our-partners').addClass("selected");
									} 
									else if (bodysID == "team") {
										$('ul#nav_787316 li.support-teams').addClass("selected");
									} 
									else {
									
									}
								});	
							},
							
							

							// update shopping cart
							shoppingCartLanguage : function() {
							  if ($("td.cartSummaryItem")[0]) {
					  
								  var cartLanguage = $("td.cartSummaryItem").text();
								  var emptyCart = "Shopping cart is empty.Shopping cart is empty."; //window.alert(cartLanguage) == "Shopping cart is empty.Shopping cart is empty." (instead of "Shopping cart is empty."
								  if (cartLanguage == emptyCart) {
									  $("td.cartSummaryItem").html("MY BASKET IS EMPTY");
								  } 
								  else {
										  var location = $("td.cartSummaryItem").find("a").attr("href");
										  var cartLanguageHyphen = $("td.cartSummaryItem").text().replace(/ /,"-");
										  var dash = cartLanguageHyphen.lastIndexOf("-");
										  var editedQuantity = cartLanguageHyphen.substr(0,dash);
										  var editedQuantity1 = editedQuantity.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
										  $("td.cartSummaryItem").html('<a href="/OrderRetrievev2.aspx">MY BASKET: \$' + editedQuantity1 + '</a>');	
								  }
							  } 
							},
							//entrepreneur, partner, team, promos					
							listpreviews : function  () {
								// entrepreneur overviews throughout the site - home, partners if visible
								if ($('div.wide-pages').is(':visible')) {
									$('div.wide-pages').each(function() {
										var src = $('a',this).attr('href')
										var a = $('<a/>').attr('href',src)
										$(this).find('img.thumbnailImage').wrap(a);
										$(this).find('img.thumbnailImage').parent().attr('class','thumbLink')
									});
								}										
								// entrepreneur list template apply link to image wide-cards and wide-pages
								if ($('body.searchTemplate')[0] && $('body#entrepreneur')[0]) {
									$('div.wide-cards').each(function() {
										var src = $('a',this).attr('href')
										var a = $('<a/>').attr('href',src)
										$(this).find('img').wrap(a);
									});
								}					
								// partner list template apply link to image
								if ($('body.searchTemplate')[0] && $('body#partner')[0]) {				
									$('div.wide-cards').each(function() {
										var src = $('a',this).attr('href')
										var a = $('<a/>').attr('href',src)
										$(this).find('img').wrap(a);
									});
								}
								// team list template apply link to image
								if ($('body.searchTemplate')[0] && $('body#team')[0]) {				
									$('div.wide-cards').each(function() {
										var src = $('a',this).attr('href')
										var a = $('<a/>').attr('href',src)
										$(this).find('img').wrap(a);
									});
								}						
							},
							//entrepreneur templates
							entrepreneurTemplates : function() {
							
					
								// entrepreneur detail template
								if ($('body#entrepreneur,.detail')[0]) {
							
									
									//If field partner is _NoPartners - remove
									if ($('span.fieldpartner')[0]) {
										if ($('span.fieldpartner a').text() == "_NoPartners") {
												$('span.fieldpartner').remove();
										}							
									}
									//move loan amount add dollar, comma and cents
									if ($('#bc-holder span.loanAmount')[0]) {				  			
									var loanTotal = $('#bc-holder span.loanAmount').html().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
									$('.amounts span.loan').html('\$' + loanTotal + '.00');
									}
									
									//move stock to "need to raise" add dollar, comma and cents
									if ($('div.instock')[0]) {
										var amountLeft = $('div.instock').html().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
										$('span.needed').text('\$' + amountLeft + '.00');
									}
									
									//check for loan status stop collecting if complete			
									if ($('#bc-holder span.loanStatus').text() == "Complete") {
										$('p.loanLabel').remove();
										$('table.productTable').remove();
									}
									
									//move images
									if ($('#bc-holder ul.entrepreneurPhotos')[0]) {					  			
										$('div.photos ul.entrepreneurPhotos').html($('#bc-holder ul.entrepreneurPhotos').html());
									}
									
									//remove sponsor holder if no image
									if ($('#leftside div.sidebarbox h3.sponsor')[0]) {
										
										if ($("#leftside a.sponsorLogoLink").attr("href").length == 0) {
											$("#leftside div.sidebarbox h3.sponsor").parent().remove()
										}
									
									}
									//If similar entrepreneurs has only one result (self) - remove
									if ($('div.sidebarbox div.categoryList').length <= 1) {
											$('div.sidebarbox div.categoryList').parent().remove();
									} 
									//remove link to current page
									else {
										var pageName = $('#titlebar h1').text();
										$('div.categoryList a').each(function() {
											if ($(this).text() == pageName) {
												$(this).remove();
											}
										});
									}
									// postings pages - video and photo emptyCart
									$('div.entr-photo,div.entr-video').each(function() {
										if ($(this).html() == "") {
											$(this).remove();
										}
									});
									
									//posting no video or photo remove divs
									if ($('.entr-photo').length) {
										if ($('.entr-photo').html() == 0) {$('.entr-photo').remove();}
									}
									if ($('.entr-video').length) {
										if ($('.entr-video').html() == 0) {$('.entr-video').remove();}
									}
								
								}
							},									
							//edit partner detail template
							partnerTemplate : function() {
		
								// detail template
								if ($('body#partner')[0]) {
								
									// list page results category
									$('div.wide-cards p small:contains(Category:)').each(function() {
										//add space to output after commas
										$(this).text($(this).text().replace(/,/g, ', '));
									});
									//detail page partner facts
									$('div.sidebarbox small').text($('div.sidebarbox small').text().replace(/,/g, ', '));
									
									//detail page no results
									$('div.sidebarbox:contains(No items found.)').each(function() {
										$(this).prev().remove();
										$(this).remove();
									});
									
									//posting no video or photo remove divs
									if ($('.entr-photo').length) {
										if ($('.entr-photo').html() == 0) {$('.entr-photo').remove();}
									}
									if ($('.entr-video').length) {
										if ($('.entr-video').html() == 0) {$('.entr-video').remove();}
									}

									
								}
							},				
							//secure zone posts
							secureZonePosts : function() {
							
		
								if ($('body#securePost')[0]) {
																	
										$('.postTitle').blur(function() {
		
											//build the date add zero to single digit days and months for listing order
											var d = new Date();						
											if (d.getMonth()+1 < 10) {
												var month = "0" + (d.getMonth()+1);
											}
											else {
												var month = d.getMonth()+1;
											}
											if (d.getDate() < 10) {
												var day = "0" + d.getDate();
											}
											else {
												var day = d.getDate();
											}
											var dateEntered = d.getFullYear() + "-" + month + "-" + day;
											var companyName = $('form span#companyName').text()
											var	postTitle = $('input.postTitle').val();
											
											
											//add elements together to build the itemName for admin
											$('input#ItemName').val(dateEntered+"-"+companyName+"~"+postTitle);
									
										});
								
								}
								
							},
							//support-portfolio
							supportPortfolio : function() {
								
								if ($('body#support-portfolio')[0] || $('body#join-team-body')[0]) {
									
									//show hide profile bio form from default page						
									if($('div.previousPost a').text()) {
										$('form.newBio').remove();
									} else {
										$('div.previousPost').remove()
									}
									
									//show hide forms on edit post						
									if($('div.editBioForm').text()) {
										$('div.spreadword').remove();
										$('div.accountpreferences').remove();
									} 
									
									//total given based on contributions total
									var totalAmount = 0;
									$('table.order-list span.total').each(function() {
										totalAmount += parseInt($(this).text().replace(/[^0-9\.]+/g,""));
									});
										
									// check if total amount is more than 0
									if (totalAmount > 0) {
										$('.sidebarbox em.totalNum').text(totalAmount);
										var totalAmountFixed = $('.sidebarbox em.totalNum').text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
										$('.sidebarbox em.totalNum').text("\$"+totalAmountFixed+".00");
										
										//edit link to invoice remove system generated "online Shop"
										$('table.order-list td.ordername').each(function() {
											var textName = $("a", this).text().split('Online Shop ')[1];
											$("a", this).text(textName)
										});										
									} else {
										$('.sidebarbox em.totalNum').text('$0.00')
									}

									//add the date and profilename to the itemname for donor bio
									$('form input.profilename').blur(function() {
										//build the date add zero to single digit days and months for listing order
										var d = new Date();						
										//month
										if (d.getMonth()+1 < 10) {
											var month = "0" + (d.getMonth()+1);
										} else {
											var month = d.getMonth()+1;
										}
										//day							
										if (d.getDate() < 10) {
											var day = "0" + d.getDate();
										}else {
											var day = d.getDate();
										}
										var dateEntered = d.getFullYear() + "-" + month + "-" + day;
										$('#ItemName').val(dateEntered + "-" + $('input.profilename').val());
									});
									

								}
							},
							// edits to support basket template
							supportbaskettemplate : function() {
								if ($("body#supportbasket")[0]) {
									//remove links off of products
									$('td.firstrow div.productitemcell a').each(function() {																			
										if ($(this).text() == "ShadeFund Operations") {
											$('div#shadefund-product').remove();
										}
										$(this).parent().text($(this).text());
										$(this).remove();
									});
									
									// reload page on remove
									$('tr.val div.productitemcell a').each(function() {
										$(this).bind('click', function() {
											location.reload();
										});
									});
									
									// no products
									if ($("#catCartDetails a.cartLink")[0]) {					  	
									  $("#catCartDetails a.cartLink").text("You have removed your donation. Return to Entrepreneurs. ");
									  $("#catCartDetails a.cartLink").attr("href" , "/entrepreneurs/index.htm");
									}
									// adjust header
									$('#top h1 a, div#menu a, div#footer a').each(function() {
										//add space to output after commas
										var currentPath = $(this).attr("href");
										
										//function to split and check if protocol
										var currentPathProtocol = currentPath.split(":")[0];
										
										if (currentPath.split(":")[1]) {} else {
										var appendpath = "http://shadefund.org" + currentPathProtocol;
											$(this).attr("href",appendpath)
										}
									});
									//adds dollar sign and change at begining and end of each input
									if ($('table.cart')[0]) {
										$('td.quantity div.productitemcell').each(function() {
											var itemValue = $(this).html();
											$(this).html("\$ " + itemValue + ".00");
										});
									}			
								}
							},
							//removes initial value
							productQuantity : function()  {
								if ($('.productTextInput').val('1')) {
									$('.productTextInput').val('');
								}
							},
							// about template fnc
							priceInputCleanUp : function() {
									// commas and change in price input
									$('div.priceInput input').bind('blur', function() {
										
										var rawAmount = $(this).val();
										// already dollar sir
										var rawDolFreeAmount = rawAmount.replace(/\$/g, '');								
										// no change please
										var splitRawAmount = rawDolFreeAmount.split(".")[0];
										//remove comma please
										var rawNoComma = splitRawAmount.replace(/[^0-9\.]+/g,"");
										$(this).val(rawNoComma)
									});			
							},				
							//checkout functions
							checkouttemplate : function() {
							  if ($("body#checkout")[0]) {
									if ($("#catCartDetails a.cartLink")[0]) {					  	
									  $("#catCartDetails a.cartLink").text("You have removed your donation. Return to Entrepreneurs. ");
									  $("#catCartDetails a.cartLink").attr("href" , "/entrepreneurs/index.htm");
									}
									$('#top h1 a, div#menu a, div#footer a').each(function() {
										//add space to output after commas
										var currentPath = $(this).attr("href");
										
										//function to split and check if protocol
										var currentPathProtocol = currentPath.split(":")[0];
										
										if (currentPath.split(":")[1]) {} else {
										var appendpath = "http://shadefund.org" + currentPathProtocol;
											$(this).attr("href",appendpath)
										}
									});
									// toggle tribute
									$('tr.tributee').hide();
									$("#tribute").change(function() {
										$("tr.tributee").toggle();
										 
									});
									//encrouage email as username
									$('input#EmailAddress').blur(function() {
										$('input#Username').val($('input#EmailAddress').val());
									});									
								
							  }
							}

		}
	};
	shadeFund.overrides.addToCart();
	shadeFund.overrides.updateItemQuantity();
	
	//$("#cart a").after("<br />");
	//$(".cartSummaryItem a").before("<br />");
	//$("#_dot").
	
	
});


