// Site Javascript/JQuery methods
////Global variables
var pageId;
var emailConfig;
//var callid = Math.round(new Date().getTime() / 1000);
//var sessID;
//var authID;
//var authURL;
var emailProg;//will pull this from the Users field in the API
var matrix = '<table cellpadding="0" cellspacing="0"></table>';//containing table for matrix
var matrixHead = '<tr><th class="order" width="90">Version</th><th class="state" width="120">Email State</th><th class="status">Status</th><th class="change" width="200">&nbsp;</th></tr>';
var matrixMonthly = ['<tr><td class="order" id="m1"><a href="?page=emailconfig_m1">Jan</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m2"><a href="?page=emailconfig_m2">Feb</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m3"><a href="?page=emailconfig_m3">Mar</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m4"><a href="?page=emailconfig_m4">Apr</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m5"><a href="?page=emailconfig_m5">May</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m6"><a href="?page=emailconfig_m6">Jun</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m7"><a href="?page=emailconfig_m7">Jul</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m8"><a href="?page=emailconfig_m8">Aug</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m9"><a href="?page=emailconfig_m9">Sep</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m10"><a href="?page=emailconfig_m10">Oct</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m11"><a href="?page=emailconfig_m11">Nov</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					  '<tr><td class="order" id="m12"><a href="?page=emailconfig_m12">Dec</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>'];//all the rows that make up the monthly emails
var matrixQuarterly = ['<tr><td class="order" id="q1"><a href="?page=emailconfig_q1">Q1</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					   '<tr><td class="order" id="q2"><a href="?page=emailconfig_q2">Q2</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					   '<tr><td class="order" id="q3"><a href="?page=emailconfig_q3">Q3</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					   '<tr><td class="order" id="q4"><a href="?page=emailconfig_q4">Q4</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>'];//allthe rows that make up the quarterly meails
var matrixSpecial = ['<tr><td class="order" id="bday"><a href="?page=emailconfig_bday">Bday</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					 '<tr><td class="order" id="new1"><a href="?page=emailconfig_new1">New Cust 1</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					 '<tr><td class="order" id="new2"><a href="?page=emailconfig_new2">New Cust 2</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>',
					 '<tr><td class="order" id="new3"><a href="?page=emailconfig_new3">New Cust 3</a></td><td class="state">New</td><td class="status">&nbsp;</td><td class="change">&nbsp;</td></tr>'];//rows for the birthday and new customer emails
////check for the users specific email program by string searching
var e_q;//quarterly
var e_m;//monthly
var e_b;//birthday
var e_n;//new customer single
var e_2;//new customer 3 step
var thisSession; 
				  
						   
/////cookie methods
function createCookie(name,value,days) {//Standard Create Cookie Method
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {//Standard Read Cookie Method
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {//Standard Erase Cookie Method
	createCookie(name,"",-1);
}
////end cookie methods
function customEmailForm(){
	$('div.calloutbox').hide();//hide "Edit This Page" div
	$('.CustomFormTable')//general form table manipulation
	.attr('rel', pageId)
	.find('th')
	.wrapInner('<td/>')
	.end()//put a TD tag inside the TH tag. Don't worry about nesting, as the next code will remove the TH tag
	.find('th td')
	.unwrap()
	.end()//TH tags are removed
	.parent()
	.appendTo('#CustomPageBody')//moves everything into CustomPageBody element to contain it
	.end()
	.find('tr')
	.each(function(i){
				   $(this).addClass('row'+i)
				   });
	$('.CustomFormTable input[type!="hidden"], .CustomFormTable textarea').each(function(i){
								   $(this).attr('tabindex',i);
								   });
	$('td label')//add class to each cell with label
	.parent()
	.addClass('labelcell');
	
	$('table.emailsetup, table.emailsetup_dev')//changes to the email setup form
	.find('#Label_Custom_EmailInformation, #Label_Custom_EmailPlan, #Label_Custom_CompanyInformation, #Label_Custom_SocialLinks')//find all Section-type cells and expand colspan.
	.parent()
	.attr('colspan', '4')
	.closest('table')
	.find('input[type="checkbox"], input[type="radio"]')//adds a class for styling
	.parent()
	.addClass('checkbox')
	.closest('table')
	.find('input[name="Custom_AffiliateID"]')
	.attr('disabled', true);
	
	$('#Label_Custom_SocialLinks')//removes empty row after Social Links
	.parent()
	.attr('colspan', '4')
	.parent()
	.next('tr')
	.remove();
	
	$('.CustomFormTable tr')
	.each(function()
				   {//set the width of each first td
				   $(this)
				   .find('td:first')
				   .css('width', '200px')
				   .children('label')
				   .css('width', 'auto')
				   .end()
				   .find('td:eq(2)')
				   .css('width', '200px')
				   .children('label')
				   .css('width', 'auto');
				   });
	////email configuration pages////
	$('table[class*="emailconfig"]')//changes to the email config form
	.find('#Label_Custom_CouponNo1, #Label_Custom_CouponNo2')
	.parent()
	.attr('colspan', '4')
	.addClass('separator');
	
	$('#Label_Custom_or')//target the special "or" cell
	.parent()
	.attr('colspan', '4');
	if($('body[class$="emailsetup"]')){ 
	$('#Label_Custom_CustomEmailAddons, #Label_Custom_SetupandBillingInformation, #Label_Custom_CompanyInformation, #Label_Custom_EmailPlan, #Label_Custom_EmailInformation')//target the separator cell
	.parent()
	.attr('colspan', '4')
	.addClass('sep_cell');
	}
	
	
	
	
	
	if($('body[class*="emailconfig"]')){//check if this is an email config form, then target separator cells
	$('#Label_Custom_EmailConfiguration, #Label_Custom_LeftColumnConfiguration, #Label_Custom_LeftColumn, #Label_Custom_RightColumnConfiguration, #Label_Custom_TipSelection, #Label_Custom_CouponConfiguration')//target the separator cell
	.parent()
	.attr('colspan', '4')
	.addClass('sep_cell');
	
	$('#Label_Custom_EmailConfiguration')
	.parent()
	.attr('colspan', '2')
	.addClass('lead_cell')
	.next('td')
	.attr('colspan', '2')
	.addClass('sep_cell lead_cell');
	
	$(' #Label_Custom_CouponConfiguration')
	.closest('tr')
	.next()
	.children('td')
	.addClass('blankrow');
	
	$('#Label_Custom_SpecialServices')
	.parent()
	.attr('colspan', '4');
	} 
	///hover effect for email template view
	$('#CustomPageBody a:first').remove();
	$('#CustomPageBody form')
	//.before('<p class="flyover"><a href="#" rel="'+webURL+'resource/resmgr/images/emailtemplate_structure.png">View HTML email template structure.</a></p>')
	;
	$('#CustomPageBody p.flyover a')	
	.mouseenter(function(){
						 
						 var imgTarg = $(this).attr('rel');
						 var linkPos = $(this).offset;
						 $(this).parent().append('<div class="flyout"><img src="'+imgTarg+'"/></div>').find('.flyout').css({'position':'absolute'});
						 })
	.mouseleave(function(){
						 
						 $('.flyout').remove()
						 })
	.click(function(){
					return;
					});
	}
	
	function formCollapse(fieldname, rownum, rowspan){
		
													
															 
		if($.isArray(fieldname) == false){
			var fieldname = [fieldname];
			
		}
		if($.isArray(rownum) == false){
			
		var rownum = [rownum];
		}
		if($.isArray(rowspan)== false){
							  
		var rowspan = [rowspan];
		}
	$.each(fieldname, function(i){
		/*$('table.CustomFormTable tr').each(function(){
													var tdcnt = $(this).children('td').toArray();
													$('input[type="text"], textarea').css('width', 250);
													if(tdcnt.length > 1){
														$(this).children('td').attr('colspan', 1).removeAttr('style');
														$(this).find('td:first').attr('width', 250);
													}
													if(tdcnt.length == 1){
														$(this).children('td').attr('colspan', 2).removeAttr('style');
													}
													$('td .deemphasize').css('width', 250);
													
													
													});*/					   
							   var rowuntil = rownum[i]+rowspan[i];
	 $('input[name="'+fieldname[i]+'"]')
							  .closest('td')
							  .attr('colspan', 4)
							  .addClass('option')
							  .prev('td')
							  .remove()
							  .end()
							  .closest('tr')
							  .nextUntil('tr.row'+rowuntil).hide()
							  .children('td')
							  .removeClass('separator');
							  $('input[name="'+fieldname[i]+'"][type="checkbox"]')
							  .click(function(){
											  if($('tr.row'+rownum[i]).css('display') == 'none'){
												$(this)
												.closest('tr')
												.nextUntil('tr.row'+rowuntil)
												.show();  
											  }else
											  {
												  $(this)												  
												  .closest('tr')
												  .nextUntil('tr.row'+rowuntil)
												  .hide();
												  }
											  });
							   })
	
		
		//('table.CustomFormTable tr:visible td:first').width(250);
	}
	
	
	
function pageNaming(string){
	var l = string.length;
	var locSearch = window.location.search;
	var locEnd = locSearch.indexOf('&');
	var locStart = (locSearch.search(string))+l;//finds page= string 
	
	if(locSearch.search(string) < 0){//if the server is using serach shortcut, only slice off after ?
		pageId = locSearch.slice(1);
	} 
	else if(locEnd == -1){//if there is no & in the search, do not use end index
		pageId = locSearch.slice(locStart);
	}
	else{//if there are other parameters in the string, stop at the & index
		pageId = locSearch.slice(locStart, locEnd);
	}
	if(!locSearch){//if the page doesn't have a search parameter, default to pathname
		pageId = window.location.pathname;//get the pathname
		var trailIndex = pageId.lastIndexOf("/");//find the last trailing slash
		var extSearch = pageId.indexOf('.');
		
		if(extSearch == -1){
			pageId = pageId.slice(1);//remove the slash in the pathname
		} else {
			pageId = pageId.slice(1,extSearch)//take everything after the slash, but before the period
		}
		if(pageId.indexOf('/')!= (-1)){
			
			var slashPos = (pageId.indexOf('/'))+1;
			pageId = pageId.substr(slashPos);
			
		}
		
		
	}
	$('body, .CustomFormTable').addClass(pageId);//add class to body tag for use in custom css and jq
	
}

/*function auth(){
	$.ajax({
	   url: 'apiProxy.aspx',
	   type: 'POST',
	   data: '<?xml version="1.0" encoding="utf-8" ?><YourMembership><Version>1.63</Version><ApiKey>'+apikey+'</ApiKey><CallID>'+callid+'</CallID><Call Method="Session.Create"></Call></YourMembership>',
	   processData: false,
	   success: function(data)
	   {
		   callid++;
		   sessID = $(data).find('SessionID').text();
		   createCookie('sessID', sessID, 0);
		   thisSession = sessID;
		   //alert(thisSession);
		   },
		   error: function(){
			   alert("Data Fail");
			   },
			   complete: function(){//once session is created, make call to bind auth token to the session. This must be done on the login function
			   $.ajax({
					  url: 'apiProxy.aspx',
					  type: 'POST',
					  data: '<?xml version="1.0" encoding="utf-8" ?><YourMembership><Version>1.63</Version><ApiKey>'+apikey+'</ApiKey><CallID>'+callid+'</CallID><SessionID>'+sessID+'</SessionID><Call Method="Auth.CreateToken"><Persist>1</Persist></Call></YourMembership>',
					  processData: false,
					  success: function(data){
						  callid++;
						  authID = $(data).find('AuthToken').text();
						  //authURL = $(data).find('GoToUrl').text();
						 // alert($(data).text());
						  var formAction = $('#aspnetForm').attr('action');//login.asppx page
						  $('#aspnetForm').attr('action', 'https://greenearthcleaning.site-ym.com/login.aspx?persist=1&authtoken='+authID);
						  },
						  error: function(){
							  alert("Data Fail");
							  }
							  });
			   }
			   });
}*/
function buildMatrix(){
	$('#apicalls').ready(function(){
	emailProg = $('#apicalls').contents().find('#emailprogram').text();//readCookie('emailprog');
								  });
	
	e_q = emailProg.search(/q/i);//quarterly
	e_m = emailProg.search(/m/i);//monthly
	e_b = emailProg.search(/b/i);//birthday
	e_n = emailProg.search(/n/i);//new customer single
	e_2 = emailProg.search('2');//new customer 3 step
	if(e_m < 0){
		$('td[id^="m"]').parent().hide();
		};
	if(e_q<0){
		$('td[id^="q"]').parent().hide();
		}
	if(e_b<0){
		$('td[id="bday"]').parent().hide();
		}
	if(e_n<0){
		$('td[id^="new"]').parent().hide();
		}
	if (e_2<0){
		$('td[id="new2"], td[id="new3"]').parent().hide();
		}
if(emailProg == ''){//no email program listed
		$('td').parent().show();
		//$('#email_matrix').html('<p>You have not set up your email program yet. Please go to the <a href="/?emailsetup">Email Program Setup Page</a> to configure your program</p>');
	}
};



/*function memdata(){
	var aSess = readCookie('sessID');
	
	var callid = Math.round(new Date().getTime() / 1000);
	//alert(authSess+'  '+callid+'  '+apikey);
	$.ajax({
		   url: 'https://greenearthcleaning.site-ym.com/apiProxy.aspx',
		   type: 'POST',
		   data: '<?xml version="1.0" encoding="utf-8" ?><YourMembership><Version>1.63</Version><ApiKey>'+apikey+'</ApiKey><CallID>'+callid+'</CallID><SessionID>'+aSess+'</SessionID><Call Method="Member.Profile.Get"></Call></YourMembership>',
		   processData: false,
		   success: function(data){
			   memID = $(data).find('ID').text();//gets the member ID. Important for the profile updating calls
			   emailProg = $(data).find('CustomFieldResponse[FieldCode = "emailprogram"] Value').text();//get the emailprogram field, which is the code of what emails the user may send
			   emailConfig = $(data).find('CustomFieldResponse[FieldCode = "emailshared"] Value').text();//gets the contents of the shared field, which has all the emails they have configured
			   alert(memID);
			  
			   if(!emailConfig){//if emailConfig is undefined due to a blank data field, fill with empty string
				   emailConfig = '';
				   }
				   createCookie('emailconfig', emailConfig, 0);
				   createCookie('emailprog', emailProg, 0);
				   //createCookie('smid', memID, 0);//Member ID goes into a session cookie
				   },
				   error: function(data){//if the data has failed, it is most likely due to an outdated session. Let the user know and then sign them out.
				  
				   alert("Session has expired. Please log in again");
				   //window.location = ''+webURL+'Logout.aspx';
				   },
				   complete: function(){//on call completion, build status matrix table on page and save variables into session cookies
				   
				  buildMatrix();
				   }
				   });
	}*/
	


function statusUpdate(){
	var check = readCookie('emailconfig');
	var changeLink = '<a href="?emailchange&targemail='+pageId+'">Request a change to this email</a>';
	if(!check){//if there is no cookie to read, then the user is here for the first time this session.
	check='';
	}
	var emailStates = check.split(',');//create array from cookie
	$.each(emailStates, function(i){//iterate
								 var start = emailStates[i].indexOf('_');//find the position of the undescore
								 var targ = '#'+emailStates[i].substr(start+1);//we want everything AFTER the underscore.
								 $('#email_martix table').ready(function(){//make sure the matrix has rendered
																		 });
								 });
	profileEmail(readCookie('emailconfig'));//write the cookie data to profile for storage. This is more imporant if the cookie has changed
	}
function profileEmail(){
		callid = (Math.round(new Date().getTime() / 1000))+1;
		var myId = readCookie('smid');
		var authSess = readCookie('sessID');
		var emailProgram = readCookie('emailprog');
		var emailCon = readCookie('emailconfig');
		$.ajax({
			   url: 'apiProxy.aspx',
			   type: 'POST',
			   data: '<?xml version="1.0" encoding="utf-8" ?><YourMembership><Version>1.63</Version><ApiKey>'+securekey+'</ApiKey><CallID>'+callid+'</CallID><SessionID>'+authSess+'</SessionID><SaPasscode>'+securepass+'</SaPasscode><Call Method="Sa.People.Profile.Update"><ID>'+myId+'</ID><CustomFieldResponses><CustomFieldResponse FieldCode="emailprogram"><Values><Value>'+emailProgram+'</Value></Values></CustomFieldResponse><CustomFieldResponse FieldCode="emailshared"><Values><Value>'+emailCon+'</Value></Values></CustomFieldResponse></CustomFieldResponses></Call></YourMembership>',
			   processData: false,
			   success: function(data){	
			   //alert($(data).find('ErrCode').text());
			   },
			   error: function(){
				   alert("Write Fail")
				   }
					   });
		}
function emailDash(){///set up email dashbaord based on users program and what has been logged as complete
		$('.emailsetup_dash #email_matrix')
		.append(matrix)//adds matrix variable string
		.find('table')//find the table contained
		.append(matrixHead)//add matrixHead variable string
		.end();
		/////iteratively unescapes each string to render as HTML
		$.each(matrixQuarterly, function(){
										 $('#email_matrix table')
										 .append(unescape((this)));
										 });
		$.each(matrixMonthly, function(){
									   $('#email_matrix table')
									   .append(unescape((this)));
									   });
		$.each(matrixSpecial, function(){
									   $('#email_matrix table')
									   .append(unescape((this)));
									   });
		//if(window.location.search == '?emailsetup_dash' || window.location.search == '?page=emailsetup_dash'){
			//buildMatrix();//Run buildMatrix function
			$('.CustomFormTable.emailsetup_dash, .CustomFormTable.email_dash_dev')
			.closest('form')//find closest Form element
			.wrap('<div id="uploadList"/>')//wrap it in a div for styling
			.parent('#uploadList')//go to parent
			.insertBefore('#email_matrix')//insert it at the top of the content window
			.find('td:first')//find first td
			.css('width', '150px')//inline style it
			.children('label')//get all the child labels
			.css('width', '100%')//inline style them
			.closest('#uploadList')//find the parent div again
			.find('.formbutton')//find the button element in it
			.appendTo('.CustomFormTable.emailsetup_dash td:last, .CustomFormTable.email_dash_dev td:last');//add it to the last TD
			//}
			}
			
function splitpane(pageTar){/////split pane function for FAQ-type pages. Supply the body class to the function
		$('#CustomPageBody p:first')
		.prependTo('#CustomPageBody');//moves the headline to the top of the main div
		$(pageTar+' #CustomPageBody h4')//find all H4 tags
		.each(function(i){
					   var count = (i+1);//increase the count so that the number matches the list item href
					   var a_content = $(this).nextUntil('h4').andSelf();//gather all siblings until the next H4, plus self
					   $(this)
					   .before('<div class="right_pane q'+count+'"/>')//add the holding div before the targeted H4
					   .nextUntil('h4')//gather all siblings until the next H4,
					   .andSelf()// plus self
					   .appendTo('div.q'+count);//add to div that was placed before target
					   
					   $('div.q'+count)
					   .hide()//hide div
					   .find('p:last a')//find last link in the content
					   .hide();//hide it
					   });
		$(pageTar+' #CustomPageBody')
		.show();
		$(pageTar+' div.q1')
		.show();//show the first answer on page load
		$('#CustomPageBody')
		.append('<div class="mobileholder" style="display: block; height: 510px;"></div><div class="left_pane" style="width: 250px; height:500px; overflow:auto;"></div>');//add left pane div to the top of main div
		
		//$(pageTar+' .headline')
		$(pageTar+' ol:first')
		//.nextUntil('h4')
		.appendTo('.left_pane');//takes the list of links and puts them in the new left pane div
		$('.left_pane a')
		.click(function(){//add function to each list item link to show proper div on click
						var myTarg = $(this).attr('href');//the link reference 
						myTarg = myTarg.substr(1);//remove the "#" from it
						
						$(pageTar+'  div.right_pane').hide();//hide ALL divs with the right_pane class
						$('div.'+myTarg).fadeIn('fast').scrollTop(0);//on click, fade in the targeted right_pane div
						$(function(){$('div.'+myTarg).jScrollPane({showArrows: true});});
						return false;//cancel href action on link
						});
		$.getScript('/resource/resmgr/scripts/jquery.jscrollpane.js', function(){
																					   
																					   $('.left_pane, .right_pane').jScrollPane({showArrows: true});
																					   });
		
		}
		
function emailConfigBuild(){
	 $('#CustomPageBody')
	 .ready(function(){
					 //$('#CustomPageBody').parent().append('<iframe id="liveview"></iframe>');
					 $('input[name="Custom_EmailConfiguration"]')
					 .attr({'value':pageId, 'readonly': true});
					 var configHold = readCookie('emailconfig');
					 //alert(configHold);
					 var testPrev = configHold.search(pageId);
					 var configArray = configHold.trim().split(',');
					 if(testPrev < 0)
					 {//page ID is not in the cookie
					 configArray.push(pageId);
					 configWrite = configArray.join(',');
					 createCookie('emailconfig', configWrite, 0);
					 }
					 });
}
function emailLogging(){
	var emailFields = new Array(); 
	emailFields.splice(0, 0, 'EmailName:'+pageId);
	createCookie(pageId, emailFields.join(','), 365);
	//alert(emailFields[0]);
$('input , textarea').blur(function(){
									var pos = $(this).attr('tabindex');
									var val =$(this).val();
									var inputId = $(this).attr('id');
									inputId = inputId.substr((inputId.lastIndexOf('_')+1));
									emailFields.splice(pos, 0, inputId+':'+escape(val));
									createCookie(pageId, emailFields.join(','), 365);
									//alert(readCookie(pageId));
									});
	
}
 var webURL = 'http://www.greenearthcleaning.com/';	
 var docpath = window.location.pathname;
				if(docpath.indexOf("/docs/") == 0){
					window.stop();
				window.location.assign('http://support.greenearthcleaning.com/Resources/Videos/spotting'+docpath);
								  }
$(document)
.ready(function(){
				//$('head script[src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"]').remove();//Remove previous JQuery call
				//$('head script[src="/combined.js?context=sp&_v=1.16"]').remove();
				//Check for the broken "doc" pathname
				//remove general registration link
				$('.calloutbox').contents().filter(function() {
														   return this.nodeType == 3;
														   })
				.wrap('<span></span>')
				.end();
/*$('a[href^="/general/register"]')
				.prevUntil('a')
				.andSelf()
				.hide();*/
				//remove dropdown on News pages
							   $('form[name!="news_category"]').show();
				pageNaming('page=');//put custom class on Body and .CustomFormTable elements
						//Navigation modification code
						 $('#LeaderNav').attr('align', 'right').wrapInner('<div class="leader_nav"/>');//put a classed div wrapper in top nav
						   $('.leader_nav').prepend('<a href="#" class="search_button">Search</a>&nbsp; | &nbsp;<a href="'+webURL+'?page=Storelocator" class="locator">Find a Store</a>&nbsp; | &nbsp;');//add store locator and search links
						    $('#LeaderNav a').each(function(){
														 if($(this).text() == 'Contact Us' && $(this).next('a').text() != 'My Profile'){
														$(this).after('&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href="/login.aspx">My Profile</a>');
														 }
														 
														 });
						  $('#Search').appendTo('.leader_nav').hide()//remove Search outside and  put it in the leadernav
						  $('.search_button')
						  .click(function(){//search link exposes or hides the search box on click
										  var thisPos = $(this).position();
										  $('#Search').css('left', thisPos.left);
										   if($('#Search')
												.is(':hidden')){
											   $('#Search')
											   .show();
											   }
											   else{
												   $('#Search')
												   .hide();
												   }
												   return false;
												   });
						   
						   $('#PageLeader').appendTo('td#Head')//move PageLeader to bottom of code, so that it renders on top.
						   
						   
						   
						   /*if(window.location.pathname == '/login.aspx'){
							   auth();
						   }*/
						  
							//page specific function calling. This should keep the load lower   
						  var pageCheck = $('body').attr('class');
						  if(pageCheck.search(/emailconfig/i) >= 0){
							  pageCheck = "emailconfig";
						  }
					
						  switch(pageCheck){
							case 'FAQs'://FAQs page
							splitpane('.FAQs');
							break;
							
							case 'FAQsDC': //Dry Cleaners FAQs page
							splitpane('.FAQsDC');
							break;
							
							case 'FabricCareTips': //Dry Cleaners FAQs page
							splitpane('.FabricCareTips');
							break;
							
							case 'emailsetup_dash': //email marketing dashboard
							emailDash();
							break;
							
							case 'emailconfig': //any of the email config pages
							customEmailForm();
							emailLogging();
							//$('#CustomPageBody').width(600);
							//$('#SpContent, #SpSubHead').removeAttr('style');
							var formtype = $('table.CustomFormTable').attr('rel');
							if(formtype.search('_q')!=-1 || formtype.search('_newcust')!= -1){//test for quarterly email page
								var fields = ['Custom_LeftColumnConfiguration','Custom_TipSelection', 'Custom_RightFieldOption'];
								var nums = [5,13,17];//starting index of the row to collapse to
								var spans = [7,3,29];//how many rows to collapse
								};
								
							if(formtype.search('_month')!=-1){//test for monthly email page
								var fields = ['Custom_LeftColumnConfiguration','Custom_RightColumnConfiguration'];
								var nums = [8,42];
								var spans = [10,11];
								//$('.row18 td').addClass('sep_cell').attr('colspan', 4);
								};
								
							if(formtype.search('_bday')!=-1||formtype.search('lapsed')!=-1){//test for bday email page 
							 var fields = ['Custom_RightColumnConfiguration'];
								var nums = [12];
								var spans = [12];
						$('tr.row11 td:first').removeClass('sep_cell').addClass('option');
								$('tr.row2 td:first')
								.removeAttr('colspan')
								.removeClass('sep_cell')
								.closest('tr')
								.nextUntil('tr.row11')
								.hide()
								.children('td')
								.removeClass('separator')
								.end()
								.end();
								$('tr.row2 td:eq(1)')
							  .find('input:eq(1)')
							  .click(function(){
											  $(this)
												.closest('tr')
												.nextUntil('.CustomFormTable tr.row11')
												.show();  
											  
											  });
							  $('tr.row2 td:eq(1)')
							  .find('input:eq(0)')
							  .click(function(){
											  $(this)												  
												  .closest('tr')
												  .nextUntil('.CustomFormTable tr.row11')
												  .hide()
											  });
							  $('tr.row13 td').removeClass('separator');
							 
							  };
								formCollapse(fields, nums, spans);//run field collapse function
							break;
							case 'emailchange'://email change request
							customEmailForm();
							emailLogging();
							break;
							
							case 'emailsetup': //Email program setup page
							 customEmailForm();
							 formCollapse('Custom_CreateaCustomPlan',4,3);
							 $('#CustomPageBody').append('<div id="tc_pane"></div>');
							 $('#tc_pane').load('?email_tc #CustomPageBody p').insertBefore('input[name="btnSubmit"]');
							 break;
							 
							 case 'emailprog_q_setup':
							 customEmailForm();
							 formCollapse('Custom_CreateaCustomPlan',4,3);
							 $('#CustomPageBody').append('<div id="tc_pane"></div>');
							 $('#tc_pane').load('?email_tc #CustomPageBody p').insertBefore('input[name="btnSubmit"]');
							 break;
							 
							 case 'emailprog_qm_setup':
							 customEmailForm();
							 formCollapse('Custom_CreateaCustomPlan',4,3);
							 $('#CustomPageBody').append('<div id="tc_pane"></div>');
							 $('#tc_pane').load('?email_tc #CustomPageBody p').insertBefore('input[name="btnSubmit"]');
							 break;
							 
							 case 'emailprog_m_setup':
							 customEmailForm();
							 formCollapse('Custom_CreateaCustomPlan',4,3);
							 $('#CustomPageBody').append('<div id="tc_pane"></div>');
							 $('#tc_pane').load('?email_tc #CustomPageBody p').insertBefore('input[name="btnSubmit"]');
							 break;
							 
							 case 'OurCountries'://Countries
							 $.getScript('/resource/resmgr/scripts/newcode.js');
							 break;
							 
							 case 'DevHome'://development home
							 $.getScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js');
							 //$.getScript('/resource/resmgr/Widget/widget.js');
							 $.getScript('/resource/resmgr/scripts/heroslider.js');
							 break;
							 
							 case 'OurVendors':
							 $.getScript('/resource/resmgr/scripts/splitContent.js');
							 $.get('/resource/resmgr/Assets/split_styles.css', function(data){
																						$('head').append('<style>'+data+'</style>');
																						});
							 break;
							 
							 case 'OurPartners':
							 $.getScript('/resource/resmgr/scripts/splitContent.js');
							 $.get('/resource/resmgr/Assets/split_styles.css', function(data){
																						$('head').append('<style>'+data+'</style>');
																						});
							 break;
							 
							 case 'DevFabricCareTips':
							 $.getScript('/resource/resmgr/scripts/splitContent.js');
							 break;
							 
							case 'Documents':
							$('#CustomPageBody').wrapInner('<div class="nodeholder"></div>').css({'height':'750px', 'overflow':'hidden'});
							$('.nodeholder table:first').width(600);
							
							break;
							
							case 'VideoTraining':
							break;
							
							case 'EmailProgram':
							$('head').append('<link href="/resource/resmgr/_emailprog/styles.css" rel="stylesheet" type="text/css" />');
							$('#SpContent_Container form:last').addClass('uploadarea').appendTo('#step4');//give upload form a class and move into content area for positioning
							$('.uploadarea .formbutton[name="btnSubmit"]').appendTo('table .CustomFormTable tr').wrap('<td>');//move submit button into upload table, wrap in new cell
							$('.uploadarea table:first')
							.width(350)
							.find('th')
							.wrap('<td class="label">')
							.end()
							.find('th')
							.contents()
							.unwrap();//replace th cell with td cell
							$('.uploadarea .label')
							.next('td')//get the next td
							.attr('colspan','1');//remove the colspan from second cell
							 
							$('#step4').height($('.uploadarea').height());
							//open add on page in new window
							   //$('.addons_opts').click(function(){
																//var target = $(this).attr('rel');
																//window.open('http://support.greenearthcleaning.com/_emailSupport/TemplateViewer/addonlib.php?'+target);
																//});
							  
							   break;
							   
							   case 'EMP_ThankYou':
							   $('#SpContent_Container form:last').addClass('uploadarea').appendTo('#step4');//give upload form a class and move into content area for positioning
							$('.uploadarea .formbutton[name="btnSubmit"]').appendTo('table .CustomFormTable tr').wrap('<td>');//move submit button into upload table, wrap in new cell
							$('.uploadarea table:first')
							.width(350)
							.find('th')
							.wrap('<td class="label">')
							.end()
							.find('th')
							.contents()
							.unwrap();//replace th cell with td cell
							$('.uploadarea .label')
							.next('td')//get the next td
							.attr('colspan','1');//remove the colspan from second cell
							 
							$('#step4').height($('.uploadarea').height());
							   break;
							   
							default:
							/*$.getScript('/resource/resmgr/scripts/jquery.jscrollpane.js', function(){
																								   $('#CustomPageBody').jScrollPane({showArrows: true});
																																			 });*/
							break;						
							  
						  }//end page naming switch
						  
						  //check for email form error page
						  
						  
						  //review these lines to see if they are needednow that we have a switch-case method
						   var configCheck = window.location.search;
						   var fieldpos = configCheck.indexOf('_');
						   var searchpos = configCheck.indexOf('=');
						   
						   if(fieldpos >= 0){
							   configCheck = configCheck.substr(0, fieldpos);
						   }
						   if (searchpos >= 0){
							   configCheck = configCheck.substr(searchpos+1)
							   }
							   if(configCheck.search('emailchange') >= 0){//check to see if we are on the email change request page
						   var targemail = configCheck.substr(configCheck.lastIndexOf('targemail=')+10);
								$('input[name="Custom_EmailConfiguration"]').attr({'value':'emailconfig_'+targemail, 'readyonly':true});									
						   }
						   //end review
						  var where = $('head').find('meta[name="visible"]').attr('content');
						   switch(where){
								   case "public":
								   $('#RightRail').remove();
								   $('#SpSubHead').remove();
								   $('#CustomPageBody, #SpContent').width('850px');
								   if($('body').attr('class')=='Storelocator'){
									   $('#CustomPageBody, #SpContent').width('890px');
								   }
								   break;
								   case "private":
								 
								   $('#CustomPageBody').width('700px');//.height(750);
								   $('#SpSubHead').width('700px');
								   break;
								  
								   default:
								   $('#SpContent,#CustomPageBody, #SpSubHead').width('700px');
								   var vis = $('body').find('div#public').attr('id');
								   if(vis){
									   
									   $('#RightRail').remove();
									   $('#SpContent, #CustomPageBody, #SpSubHead').width('850px');
								   }
								   break;
							   }
						  
						  
						
						 
							   $('#HpFeature').empty();//remove slideshow
							   $('#PageContainer td').has('#HpFeature').css('height','442px').find('table').has('#HpFeature').remove();
							   $('.spacer_1h').parent('tr').remove();
							   //$('body br:last').prev().andSelf().remove();
							   $('td').has('#LeftColumn').css('height', '600px');
							   
							   ////If this is a print preview window, turn off backgrounds to make it white
							   $('body[class^="PrintView=1"]').css('background', 'none');
							  
							 
							   //$('#Foot').text().hide();
							   $('#Foot').html($(' .AffiliateCenter, #gec_footer, #tipwidget'));
							   //only for the thank you submission page
							  
							  $('body[class^="id="] #step4').load('/general/custom.asp?page=email_uploadonly #SpContent_Container form', function(){
																																				  $('#step4 form td:first').attr('colspan','1');//remove the colspan from second cell
																																				  $('#step4 form table:first')
																																				  .find('th')
																																				  .wrap('<td class="label">')
																																				  .end()
																																				  .find('th')
																																				  .contents()
																																				  .unwrap();
																																			$('#step4 .formbutton[name="btnSubmit"]').appendTo('.CustomFormTable tr').wrap('<td>')	  
																																				  });
							   
							   });


