// Javascript for admin logged in people only
// app_domain is the apps' domain set in the index files of the sites

$(function(){
	
	////////////////////////////
	// delete a page content
	///////////////////////////
	$('.delete_page_content').click(function () { 
	
		var page_content_id = $(this).attr('page_content_id');
		var page_id = $(this).attr('page_id');
		
		var response = $.ajax({
			type: "POST",
			data: "action=delete&page_content_id=" + page_content_id +"&page_id="+ page_id,
			beforeSend: function(){
				var ok = confirm("Are you sure want to Delete This Content from this Page?");
				
				if(!ok){ return false;}
				},
			error: function(){alert("Content has not been deleted. Please try again or contact SDR");
				alertResponse(response.responseText);
			},
			success: function()
				{ 
				// deletion was success
				// remove the pages content from the page
				$("#page_content_"+page_content_id).remove(); 
				$("#page_content_tab_"+page_content_id).remove(); 
				}
			});
		return false;	 	
		
	}); // end delete_page_content.click


});




///////////////////////////////////
////////  Handles next and previous buttons within tabbed navigation
//////////////////////////////////
$(function(){
	$('.next').click(function() { 
		 var $tabs = $('.contentTabs'); 
		 var selected = $tabs.tabs( "option", "selected" ) + 1;
		 $tabs.tabs("option","selected",selected);
		 return false; 
		 });

	$('.previous').click(function() { 
		 var $tabs = $('.contentTabs'); 
		 var selected = $tabs.tabs( "option", "selected" ) - 1;
		 $tabs.tabs("option","selected",selected);
		 return false; 
		 });

});




///////////////////////////////////
////////  Inventory Image Uploader Configuration
//////////////////////////////////
$(function(){
if($("#imageUpload_inventory").length)
	{
	new AjaxUpload('#imageUpload_inventory', {
		  // Location of the server-side upload script
		  action: domain+'Inventory.php',
		  // File upload name
		  name: 'userfile',
		  // Additional data to send
		  data: {
			folder_id : $('#folder_id').attr('value'),
			action : 'image_upload'
		  },
		  // Submit file after selection
		  autoSubmit: true,
		  // The type of data that you're expecting back from the server.
		  // Html (text) and xml are detected automatically.
		  // Only useful when you are using json data as a response.
		  // Set to "json" in that case.
		  responseType: false,
		  // Fired after the file is selected
		  // Useful when autoSubmit is disabled
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onChange: function(file, extension){
			 //alert(file);
			  var dirtyFileName = file;
			  file = cleanFileName(file);
			  var fileID = file.split(".");
			  var folder_id = $('#folder_id').attr('value');
			  //alert(fileID);
				// Clear the 'Upload Images Here!' text 
				$('#uploadTitle').empty();
				$('#saveThisBoat').attr("disabled","disabled");
				// create table
				$('#uploadContent').prepend('\
				<table class="tableIU" id="image-table-'+fileID[0]+'">\
					<tr>\
						<td class="topTd">\
							<div class="leftContainerIU">\
								<span class="example">Image Filename:</span><br>\
								<span>'+dirtyFileName+'</span><br>\
								<img style="margin-left:16px;" id="image-'+fileID[0]+'" src="'+images_app_url+'loader100px.gif" ><br>\
								\
								<span>\
									<input type="hidden" name="file_names[]" value="'+file+'" >\
									<input type="radio" name="is_main_image" value="'+file+'" >Is Main Image?\
								</span><br />\
								\
								<p>\
									<input type="button" value=" Delete This Image " image_id="'+fileID[0]+'" class="delete_inventory_image" >\
								</p>\
							</div>\
						</td>\
						\
						<td>\
							<div class="rightContainerIU">\
								<p>\
									<label for="imageTitle-'+fileID[0]+'">Image Title:<span class="red">*</span></label><br />\
									<input type="text" id="imageTitle-'+fileID[0]+'" class="textboxWide" name="image_titles[]" value="" ><br>\
									<span class="example">ex: Bow Storage on this boat is Amazing!</span>\
								</p>\
								\
								<p>\
									<label for="imageDescription">Image Description:</label><br>\
									<textarea rows="5" name="imaage_descriptions[]" id="imageDesc-'+fileID[0]+'" cols="40" ></textarea> <br>\
									\
									<span class="example">ex: Chaparral\'s are known for their Bow Storage, you will not find another brand with this much storage....etc.</span>\
								</p>\
							\
							</div>\
						</td>\
					</tr>\
				</table>'); 
				
				// Change the 'Upload Images Here!' text 
				$('#uploadTitle').css('color','#ff0000');
				$('#uploadTitle').append("Upload Another Image");
				
			  },
		  // Fired before the file is uploaded
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onSubmit: function(file, extension) {},
		  // Fired when file upload is completed
		  // @param file basename of uploaded file
		  // @param response server response
		  onComplete: function(file, response) {
			  file = cleanFileName(file);
			  var fileID = file.split(".");
			  //alert(fileID[0]);
			  var folder_id = $('#folder_id').attr('value');
				//var folder_id = response;
				//var folder_id = $('#folder_id').attr('value', folder_id);
				
				
				// have problem here.  Need to use sub-domain http://images.domain..../images_inventory/folder_id/180px/file.jpg
				var imgURL = images_inventory_url+folder_id+"/180px/"+file;
				
				//alert(imgURL);
				// here we change the image trigger value so the php script knows to re-pro zip files
				$('#image_trigger').attr("value","1");
				
				$('#image-'+fileID[0]).attr("src",imgURL);
				
				$('#saveThisBoat').removeAttr('disabled');
				
				}
		}); // end image upload script
	} // end if eleemnt present
});



///////////////////////////////////
////////  Inventory -- when a boat category dropdown is changed
///////  we show the proper boat types checkboxes
//////////////////////////////////
$(function(){
	
	$("#boat_category_id").change(function() {
		// hide all boat types
		$(".boat_types").css("display","none");
		// show the correct boat type
		$("#boat_type-"+$(this).val()).css("display","block");
		$("#boat_type").css("display","block");
		});// end change

}); // end boat category change




//////////////////////////////////////////
///////// Delete Image from Inventory ////////////////////
////////////////////////////////////////
$(function(){
	$(".delete_inventory_image").click(function() {
	
		var image_id = $(this).attr("image_id");
	
		var response = $.ajax({
			type: "POST",
			url: domain+'Inventory.php',
			data: "action=delete_image&image_id=" + image_id,
			beforeSend: function(){
				var ok = confirm("Are you sure want to Delete This Image?");
				
				if(!ok){ return false;}
				},
			error: function(){alert("Image has not been deleted. Please try again or contact SDR");
				alertResponse(response.responseText);
			},
			success: function()
				{ 
				// remove the image table from the page
				$("#image-table-"+image_id).remove(); 
				return false;
				}
			});
		 	
	}); // end click

}); // end deleteImage



//////////////////////////////////////////
///////// Rotate an Inventory image 
////////////////////////////////////////
$(function(){
	$(".rotate_inventory_image").click(function() {		

		var file_name = $(this).attr("file_name");
		var degrees = $(this).attr("degrees");
		var image_id = $(this).attr("image_id");

		var folder_id = $('#folder_id').attr('value');
		
		// set image to loader
		var imgURL = images_app_url+'loader100px.gif';
		$('#image-'+image_id).attr("src",imgURL);
		
		var response = $.ajax({
			type: "POST",
			url: domain+'Inventory.php',
			data: "action=rotate_image&file_name=" + file_name + "&degrees=" + degrees +"&folder_id=" + folder_id,
			beforeSend: function(){
				
				},
			error: function(){alert("Image has not been rotated. Please try again or contact SDR");
				alert(response.responseText);
			},
			success: function()
				{ 
				// show the new image
				// have to use random query string to keep from caching.
				var randomnumber=Math.floor(Math.random()*1000)				
				//var newImgURL = domain+"images/inventoryImages/"+folderID+"/180px/"+file+"?id="+randomnumber;
				// get the new url for the image and assign the source
				var newImgURL = images_inventory_url+folder_id+"/180px/"+file_name+"?id="+randomnumber; 
				//alert(newImgURL);
				$('#image-'+image_id).attr("src",newImgURL);
				return false;
				}
			});
	}); //end click
}); // end function
	

////////////////////////////////////////////////////////
//////////////// Blog Functions
////////////////////////////////////////////////////////


///////////////////////////////////
////////  Blog Image Uploader Configuration
//////////////////////////////////
$(function(){
if($("#imageUpload_blog").length)
	{
	new AjaxUpload('#imageUpload_blog', {
		  // Location of the server-side upload script
		  action: domain+'Blog.php',
		  // File upload name
		  name: 'userfile',
		  // Additional data to send
		  data: {
			folder_id : $('#folder_id').attr('value'),
			action : 'image_upload'
		  },
		  // Submit file after selection
		  autoSubmit: true,
		  // The type of data that you're expecting back from the server.
		  // Html (text) and xml are detected automatically.
		  // Only useful when you are using json data as a response.
		  // Set to "json" in that case.
		  responseType: false,
		  // Fired after the file is selected
		  // Useful when autoSubmit is disabled
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onChange: function(file, extension){
			 //alert(file);
			  var dirtyFileName = file;
			  file = cleanFileName(file);
			  var fileID = file.split(".");
			  var folder_id = $('#folder_id').attr('value');
			  //alert(fileID);
				// Clear the 'Upload Images Here!' text 
				$('#uploadTitle').empty();
				$('#saveThisBoat').attr("disabled","disabled");
				// create table
				$('#uploadContent').prepend('\
				<table class="tableIU" id="image-table-'+fileID[0]+'">\
               <tr>\
                    <td class="topTd">\
                         <div class="leftContainerIU">\
                              <span class="example">Image Filename:</span>\
                              <br>\
                              <span>'+dirtyFileName+'</span>\
                              <img id="image-'+fileID[0]+'" src="'+images_app_url+'loader100px.gif">\
                              <span><br />\
                                   <input type="hidden" name="fileNames[]" value="'+file+'">\
                                   <input type="hidden" name="imageID[]" value="">\
                                   <input type="radio" name="isMainImage" value="'+file+'">\
                                   Is Main Image?\
                                   <p>\
                                        <input type="button" value=" Delete This Image ">\
                                   </p>\
                              </span>\
                         </div> <!--End <div class="leftContainerIU">-->\
                    </td>\
                    <td>\
                         <div class="rightContainerIU">\
                              <p>\
                                   <label for="imageTitle-'+fileID[0]+'">Image Title:<span class="red">*</span>\</label><br>\
                                   <input type="text" id="imageTitle-'+fileID[0]+'" class="textboxWide" name="imageName[]" value=""><br>\
                                   <span class="example">ex: Bow Storage on this boat is Amazing!</span>\
                              </p>\
                              <p class="spacey">\
                                   <label for="imageDescription">Image Description:</label><br>\
                                   <textarea rows="5" name="imageDesc[]" id="imageDesc-'+fileID[0]+'" cols="40" ></textarea>\
                                   <br>\
                                   <span class="example">ex: Chaparral\'s are known for their Bow Storage, you will not find another brand with this much storage....etc.</span>\
                              </p>\
                         </div> <!--End <div class="rightContainerIU"> -->\
                    </td>\
               </tr>\
          </table>'); 
				
				// Change the 'Upload Images Here!' text 
				$('#uploadTitle').css('color','#ff0000');
				$('#uploadTitle').append("Upload Another Image");
				
			  },
		  // Fired before the file is uploaded
		  // You can return false to cancel upload
		  // @param file basename of uploaded file
		  // @param extension of that file
		  onSubmit: function(file, extension) {},
		  // Fired when file upload is completed
		  // @param file basename of uploaded file
		  // @param response server response
		  onComplete: function(file, response) {
			  file = cleanFileName(file);
			  var fileID = file.split(".");
			  //alert(fileID[0]);
			  var folder_id = $('#folder_id').attr('value');
				//var folder_id = response;
				//var folder_id = $('#folder_id').attr('value', folder_id);
				
				
				// have problem here.  Need to use sub-domain http://images.domain..../images_inventory/folder_id/180px/file.jpg
				var imgURL = images_blog_url+folder_id+"/180px/"+file;
				
				//alert(imgURL);
				// here we change the image trigger value so the php script knows to re-pro zip files
				$('#image_trigger').attr("value","1");
				
				$('#image-'+fileID[0]).attr("src",imgURL);
				
				//$('#saveThisBoat').removeAttr('disabled');
				
				}
		}); // end image upload script
	} // end if eleemnt present
});

//////////////////////////////////////////
///////// Delete Image from Blog ////////////////////
////////////////////////////////////////
$(function(){
	$(".delete_blog_image").click(function() {
	
		var image_id = $(this).attr("image_id");
	
		var response = $.ajax({
			type: "POST",
			url: domain+'Blog.php',
			data: "action=delete_image&image_id=" + image_id,
			beforeSend: function(){
				var ok = confirm("Are you sure want to Delete This Image?");
				
				if(!ok){ return false;}
				},
			error: function(){alert("Image has not been deleted. Please try again or contact SDR");
				alertResponse(response.responseText);
			},
			success: function()
				{ 
				// remove the image table from the page
				$("#image-table-"+image_id).remove(); 
				return false;
				}
			});
		 	
	}); // end click

}); // end deleteImage

//////////////////////////////////////////
///////// Rotate an Inventory image 
////////////////////////////////////////
$(function(){
	$(".rotate_blog_image").click(function() {		

		var file_name = $(this).attr("file_name");
		var degrees = $(this).attr("degrees");
		var image_id = $(this).attr("image_id");

		var folder_id = $('#folder_id').attr('value');
		
		// set image to loader
		var imgURL = images_app_url+'loader100px.gif';
		$('#image-'+image_id).attr("src",imgURL);
		
		var response = $.ajax({
			type: "POST",
			url: domain+'Blog.php',
			data: "action=rotate_image&file_name=" + file_name + "&degrees=" + degrees +"&folder_id=" + folder_id,
			beforeSend: function(){
				
				},
			error: function(){alert("Image has not been rotated. Please try again or contact SDR");
				alert(response.responseText);
			},
			success: function()
				{ 
				// show the new image
				// have to use random query string to keep from caching.
				var randomnumber=Math.floor(Math.random()*1000)				
				//var newImgURL = domain+"images/inventoryImages/"+folderID+"/180px/"+file+"?id="+randomnumber;
				// get the new url for the image and assign the source
				var newImgURL = images_blog_url+folder_id+"/180px/"+file_name+"?id="+randomnumber; 
				//alert(newImgURL);
				$('#image-'+image_id).attr("src",newImgURL);
				return false;
				}
			});
	}); //end click
}); // end function






///////////////////////////////////////////////////////////////
// this populates the user form when the username is clicked from the list.
// or will clear the list if new user is wanted to be added
///////////////////////////////////////////////////////////////
$(function(){
$(".user_selector").click(function()
  {
	//alert($(this).attr("user_id"));
	// set the selected users background to a color
	//$(this).css("background","red");
	var user_id = $(this).attr("user_id");
	
	// if user_id is 0 we want to clear all form fields to get ready for new user
	if(user_id == 0)
		{
		// show and hide some stuff
		// hide the 'add user' button that clears the form, this is done to prevent user input error (deleting what you already did)
		//$(this).hide();
		// hide and show proper buttons
		$(".user_save").show();
		// empty the form
		$("#user_id").val('');
		//$("#user_location_id").reset();
		$("#user_name").val('');
		$("#user_email").val('');
		$("#user_phone").val('');
		$("#user_mobile_phone").val('');
		$("#user_mobile_carrier").val('');
		$("#user_pass").val('');
		// empty out the name on the access/roles tab
		$(".user_name_display").empty();
		// uncheck all the checkboxes
		$.each($(".roles_checkbox"),function(){
			//alert(role);
			$(this).removeAttr("checked");
			});
		$.each($(".access_checkbox"),function(){
			//alert(role);
			$(this).removeAttr("checked");
			});

		}
	else
		{
		// hide and show proper buttons
		$(".user_save").show();

		// display the users name on all tabs so we know who we are editing
		$(".user_name_display").text($("#name-"+user_id).val());
		
		$("#user_id").val(user_id);
		$("#user_name").val($("#name-"+user_id).val());
		$("#user_email").val($("#email-"+user_id).val());
		$("#user_phone").val($("#phone-"+user_id).val());
		$("#user_mobile_phone").val($("#mobile_phone-"+user_id).val());	
		$("#user_mobile_carrier").val($("#mobile_carrier-"+user_id).val());
		$("#user_pass").val('');

		$("#user_location_id").val($("#user_location_id-"+user_id).val());
		
		// check the proper status box
		$("#user_status-"+$("#status-"+user_id).val()).attr("checked", "true");
		
		var SDR_roles = $("#user_SDR_roles-"+user_id).val().split(',');
		var SDR_access = $("#user_SDR_access-"+user_id).val().split(',');
		
		// uncheck all the checkboxes
		$.each($(".roles_checkbox"),function(){
			//alert(role);
			$(this).removeAttr("checked");
			});
		$.each($(".access_checkbox"),function(){
			//alert(role);
			$(this).removeAttr("checked");
			});
		
		$.each(SDR_roles,function(k, role){
			//alert(role);
			$("#SDR_role-"+role).attr("checked", "true");
			});
		
		$.each(SDR_access,function(k, access){
			//alert(access);
			$("#SDR_access-"+access).attr("checked", "true");
			});
		}//end else user id present
  }); // end user select
  
  

///////////////////////////
//// when a role is checked we try to auto-populate the accesses to default permissions
///////////////////////////
$(function(){
$(".roles_checkbox:input").click(function(){
	//alert('role clicked');
	// if this is checked
	if($(this).is(":checked"))
		{
		var role_id = $(this).val();
		// cycle through all the default access levels
		$.each(roles_accesses,function(k, role){
			//alert(k);
			//alert(access);
			if(role_id == role['role_id'])
				{
				//alert(role['access_id']);
				$("#SDR_access-"+role['access_id']).attr("checked","true");
				//alert($("#SDR_access-"+role['access_id']).is(":checked"));
				}
			});
		}
	});
}); // end role checkbox click
}); 



////////////////////////////////////////////////
//////////// Deletes a User
////////////////////////////////////////////////////////

$(function(){
$(".user_delete").click(function(){
	//this is the id of the specific form that was submitted (name)
	var id = $(this).attr('name');
	
	// disables the submit button
	var $that = $(this);
	var submitButton = $that.find("input[type='submit']");
	btnText = $(submitButton).attr("value");
	$(submitButton).attr("value", " Please Wait... ");
	$(submitButton).attr("disabled", "disabled"); 
	
	// get the info we need to delete a user
	var user_id = $("#user_id").val();
			
	var response = $.ajax({
		type: "GET",
		url: domain+"Salesforce.php",
		data: "action=delete&user_id=" + user_id,
		beforeSend: function(){
				var ok = confirm("Are you sure want to Delete This User?");
				
				if(!ok){ return false;}
				},
		error: function(){ fail("User has NOT been updated. Please Contact an adminstrator.", id);
			alertResponse(response);
		},
		success: function(del)
			{ 
			// This sets the uniqueID field so the user can be edited before the form is cleared
			if(response.responseText != 0)
				{	
				//alert(response.text);
				
						

				// remove the user from the list and clear the form
				$(".user_save").show();
				// empty the form
				$("#user_id").val('');
				//$("#user_location_id").reset();
				$("#user_name").val('');
				$("#user_email").val('');
				$("#user_phone").val('');
				// empty out the name on the access/roles tab
				$(".user_name_display").empty();
				// uncheck all the checkboxes
				$.each($(".roles_checkbox"),function(){
					//alert(role);
					$(this).removeAttr("checked");
					});
				$.each($(".access_checkbox"),function(){
					//alert(role);
					$(this).removeAttr("checked");
					});
				
				$("#user_list-"+response.responseText).remove();	
					
				$("#location_manager_user_list").append(new_user);
				
				
				success("Successfully Deleted.", id);
				
				// sets buttons back enabled
				$that.find("input[type='submit']").attr("value", btnText);
				$that.find("input[type='submit']").removeAttr('disabled');
				
				
				
				
				//alertResponse(response);
				}
				
			else
				{fail("An error has occurred, please try again or notify SDR", id);
				// sets buttons back enabled
				$that.find("input[type='submit']").attr("value", btnText);
				$that.find("input[type='submit']").removeAttr('disabled');
				alertResponse(response);
				}
			}
		
		});
	return false;
}); // end role checkbox click
}); 


////////////////////////////////////////////////
//////////// Adds or updates a user
////////////////////////////////////////////////////////
$(function(){
$("#user_management_form").submit(function() {

	// disables the submit button
	var $that = $(this);
	var submitButton = $that.find("input[type='submit']");
	btnText = $(submitButton).attr("value");
	$(submitButton).attr("value", " Please Wait... ");
	$(submitButton).attr("disabled", "disabled"); 
	
	
	// these will be used when populating hidden fields after the save/update
	// here we get all the access levels that were checked and convert them to an array, then csv
	var SDR_access_array = [];
		 $('#user_access_list :checked').each(function() {
		   SDR_access_array.push($(this).val());
		 });
	var SDR_access = SDR_access_array.join(',');
	
	// here we get all the roles that were checked and convert them to an array, then csv
	var SDR_role_array = [];
		 $('#user_role_list :checked').each(function() {
		   SDR_role_array.push($(this).val());
		 });
	var SDR_role = SDR_role_array.join(',');
		
	var str = $(this).serialize();
	
	var response = $.ajax({
		type: "POST",
		url: domain+"Salesforce.php",
		data: str,
		
		error: function(){ fail("User has NOT been updated. Please Contact an adminstrator.", id);
			alertResponse(response);
		},
		success: function(del)
			{ 
			// This sets the uniqueID field so the user can be edited before the form is cleared
			if(response.responseText != 0)
				{	
				//alert(response.text);
				// closes the loading wheel visual
				//$("#loadingWheel").fadeTo("medium", 0); 
								

				// add a user to the list on the left
				// we will get the user_id back from the ajax query
				// if there was no user id we need to add this new user to the user list
				if(!$("#user_id").val())
					{
					$("#user_id").val(response.responseText);
	
					var new_user = '\
						<li style="background-color:#{cycle values="ffffff,f7f7f7"};" class="user_selector location_manager_user_list" user_id="'+response.responseText+'">\
							'+$("#user_name").val()+'\
							<input type="hidden" name="user_list_id[]" value="'+response.responseText+'" />\
							<input type="hidden" name="user_list_name[]" value="'+$("#user_name").val()+'" id="name-'+response.responseText+'" />\
							<input type="hidden" name="user_list_email[]" value="'+$("#user_email").val()+'" id="email-'+response.responseText+'" />\
							<input type="hidden" name="user_list_phone[]" value="'+$("#user_phone").val()+'" id="phone-'+response.responseText+'" />\
							<input type="hidden" name="user_list_mobile_phone[]" value="'+$("#user_phone").val()+'" id="mobile_phone-'+response.responseText+'" />\
							<input type="hidden" name="user_list_mobile_carrier[]" value="'+$("#user_phone").val()+'" id="mobile_carrier-'+response.responseText+'" />\
							<input type="hidden" name="user_list_SDR_roles[]" value="'+SDR_role+'" id="user_SDR_roles-'+response.responseText+'" />\
							<input type="hidden" name="user_list_SDR_access[]" value="'+SDR_access+'" id="user_SDR_access-'+response.responseText+'" />\
						</li>\
					';
					}
					
				// else this was an existing user so we need to update any changed info in their list view
				else
					{
					var user_id = $("#user_id").val();
					
					$("#name-"+user_id).val($("#user_name").val())
					$("#email-"+user_id).val($("#user_email").val())
					$("#phone-"+user_id).val($("#user_phone").val())
					$("#mobile_phone-"+user_id).val($("#user_mobile_phone").val())
					$("#mobile_carrier-"+user_id).val($("#user_mobile_carrier").val())
					////////////////////////////////////////////////////////////////problem here !!!!!!!!!!!!!!!!!!!!
					$("#user_SDR_roles-"+user_id).val(SDR_role)
					$("#user_SDR_access-"+user_id).val(SDR_access)
						
					}
					
				$("#location_manager_user_list").append(new_user);
			
				success("Successfully Saved.");

				// sets buttons back enabled
				$that.find("input[type='submit']").attr("value", btnText);
				$that.find("input[type='submit']").removeAttr('disabled');

				//alertResponse(response);
				}
				
			else
				{fail("An error has occurred, please try again or notify SDR");
				// sets buttons back enabled
				$that.find("input[type='submit']").attr("value", btnText);
				$that.find("input[type='submit']").removeAttr('disabled');
				alertResponse(response);
				}
			}
		
		});
	return false;
	
	});
}); // end function






///////////////////////////////////////////////////////////////
/////// Global datepicker function class
/////// Used in blogs and appointment system
///////////////////////////////////////////////////////////////


$(document).ready(function() {
	if($(".datepicker").length)
	{
		$(".datepicker").datepicker();
	};
});







///////////////////////////////
///// initiates wysiwyg rich text editor
//// utilized in Blog system
//////////////////////////////
$(document).ready(function() {
	if($(".wysiwyg").length)
	{
		$(function()
		{
			$('.wysiwyg').wysiwyg(
			{
				controls : {
				justifyLeft: { visible : true },
				justifyCenter: { visible : true },
				justifyRight: { visible : true },
				justifyFull: { visible : true },
				increaseFontSize: { visible : false },
				decreaseFontSize: { visible : false },
				removeFormat: { visible : false },
				separator01 : { visible : false },
				separator02 : { visible : false  },
				separator03 : { visible : false  },
				separator04 : { visible : false  },
				separator05 : { visible : false },
				separator06 : { visible : false },
				separator07 : { visible : false },
				separator08 : { visible : false },
				separator09 : { visible : false },
				separator10 : { visible : false },
				html: {
						visible: true,
						exec: function()
						{
							if(this.viewHTML){
							  this.setContent($(this.original).val());
							  $(this.original).hide();
							  $(this.editor).show();
							}
							else{
							  this.saveContent();
							  $(this.original).show();
							  $(this.editor).hide();
							}
				
							this.viewHTML = !( this.viewHTML );
						}
				}
				
				}
			});
		});
	};
});






//////////////////////////////////////////////////////////
// sets accordion behaviour on leads page////////////////
//////////////////////////////////////////////////////////


$(function(){  
  $('.leadOpenToggle').click(function() {
	  
		// update leads updated status
		openLead($(this).attr("lead_id"));
		$(this).next().slideToggle('fast');
		});
});








//////////////////////////////////////////////////////////
// sets a global toggle next behavior.  ANy element with this class will control the view of the next element
//////////////////////////////////////////////////////////
$(function(){ 
$('.toggleNext').click(function() {
	$(this).next().slideToggle('fast');
	});
});


/////////////////////////////////////
///// updates leads updated status ie, last opened////
///////////////////////////////////////
function openLead(lead_id){	
	
	//alert(lead_id);
	var leadOpened = $('#leadOpened-'+lead_id).attr('value');
	
	// if this is a new lead or the lead is already open return success
	if(lead_id == 1234 || $('#leadOpened-'+lead_id).attr("value") == 1)
		{
		return 1;	
		}
	
	else
		{
		var response = $.ajax({
			type: "POST",
			url: domain+'Leads.php',
			data: "action=open&lead_id="+lead_id,
			error: function(){
					//$('#envelope'+leadID).attr("src","../../images/envelopeOpen.png");
				alert("lead status not changed, please contact adminstrator");
				alert(response.responseText);
			},
			success: function(del)
				{ 
				if(response.responseText == 1)
					{
					// if opened image is 'closed', change opened image from closed to open
					$('#envelope'+lead_id).attr("src",images_app_url+"icons/envelopeOpen.png");
					 $('#leadOpened-'+lead_id).attr("value", "1")
					//alertResponse(response);
					}
				else
					{
					$('#envelope'+lead_id).attr("src",images_app_url+"icons/envelopeClosed.png");
					//alertResponse(response);
					}
				}
			
			});
		}
	return false;
}





///////////////////
/// Function to populate Email template editor upon change of drop down
// this also populated the vars inside the template
///////////////////
$(function(){ 
$("select.emailTemplate").change(function(){
	//alert ($(this).attr('id'));
     // starts the loading wheel visual
	//$("#loadingWheel").fadeTo("medium", 1); 
	
	
	
	
	var selectId = $(this).attr('id');
	var idSplit = selectId.split("-");
	var lead_id = idSplit[1];
	
	//alert(selectId);
	//alert(leadID);
	//alert(salesman);
	
	//alert('#name-'+leadID);
	
	// these two are to be used for new leads
	var name     	= $('#name-'+lead_id).attr('value');
	//var salesman 	= $("#salesman-"+leadID+" option:selected").attr('value');
	var user_id 	= $("#salesman-"+lead_id).attr('value');
	
	//alert (name);
	//alert (salesman);
	
	// this gets the value of the select box selected option
	var template_id = $("#emailTemplate-"+lead_id+" option:selected").attr('value');
	
	//alert("uniqueID=" + templateID + "& leadID=" + leadID + "& name=" + name + "& salesman=" + salesman);
	
	
		var response = $.ajax({
			type: "POST",
			url: domain+"Email-Templates.php",
			data: "action=get_populated_template&template_id=" + template_id + "&lead_id=" + lead_id + "&name=" + name + "&user_id=" + user_id,
			error: function(){ fail("There has been an error retrieving the Email Template, please try again.  If problem persists please contact SDR.");
				//alertResponse(response);
			},
			success: function(del)
				{ 
				if(response.responseText)
					{
					//alertResponse(response);
					
					var emailJSON = eval("(" + response.responseText + ")");
					var emailBody = emailJSON.emailBody;
					
					//alert(emailBody);
					//eval("(" + jsonData1 + ")")
					
					//alert(emailJSON.subject);
			 		$('#subject-'+lead_id).attr('value', emailJSON.subject);
					
					// populate textarea with response 
			 		$("#emailContent-"+lead_id).val(emailJSON.tpl_source);

					 //$("#emailContent-"+leadID).wysiwyg({
				
					//$("#emailContent-"+leadID + 'IFrame').contents().find('body').html(emailJSON.emailBody);
					$("#emailContent-"+lead_id).wysiwyg('setContent', emailJSON.tpl_source);


					//$("#emailTemplate").value = response.responseText;
					//$("#emailContent-"+leadID).append(" tab to view/edit this lead.");



					
					
					//ajaxMCELoad(emailJSON.emailBody, leadID);
					//$("#loadingWheel").fadeTo("medium", 0); 
					}
				else
					{
					alertResponse(response);
					}
				}
			
			});
	
	return false;

	});
});





//////////////////////////////////////////
///////// Send Email to lead ////////////////////
////////////////////////////////////////

$(function(){
$('.sendEmailToLead').click(function () { 
		
	var lead_id = $(this).attr("lead_id");
	
	var subject    = $('#subject-'+lead_id).attr('value'); 
	// get content of mce editor
	
	//var content = ajaxMCEGet(id);
	var content = 	$("#emailContent-"+lead_id).val();		 		
	//alert(content);
	content = content.replace(/%/,"&#37;");
	
	
	var content = 	encodeURIComponent(content);
	
		var response = $.ajax({
			type: "POST",
			url: domain+"Leads.php",
			data: "action=send_lead_email&lead_id=" + lead_id + "&content="+ content + "&subject="+ subject,
			error: function(){alert("lead status not emailed, please contact adminstrator");
				alertResponse(response);
			},
			success: function()
				{ 
				if(response.responseText)
					{
					// if opened image is 'closed', change opened image from closed to open
					alert("Email has been sent");
					//alert(response.responseText);
					}
				else
					{
					alert("Email has not been sent");
					alert(response.responseText);}
				}
			});
	return false;	 	

	}); // end listeners
}); // end function



////////////////////////////////////////////////
//////////// Adds or updates a new lead //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
$(function(){ 
$("form.addUpdateLead").submit(function() {
	
	//alert('im firing');
	//this is the id of the specific form that was submitted (name)
	var lead_id = $(this).attr('name');
	//alert(id);
	// disables the submit button
	var $that = $(this);
	var submitButton = $that.find("input[type='submit']");
	btnText = $(submitButton).attr("value");
	$(submitButton).attr("value", " Please Wait... ");
	$(submitButton).attr("disabled", "disabled"); 
	
	// starts the loading wheel visual
	//$("#loadingWheel").fadeTo("medium", 1);  

	
	
	//'[@name=foo]'
	// we want to store the values from the form input box, then send via ajax below
	//var uniqueID	= id;
	//alert(uniqueID);
	
	var str = $(this).serialize();
	
		var response = $.ajax({
			type: "POST",
			url: domain+"Leads.php?action=save_ajax",
			data: str,
			
			error: function(){ fail("Lead has NOT been updated. Please Contact an adminstrator.", id);
				alertResponse(response);
			},
			success: function(del)
				{ 
				// This sets the uniqueID field so the user can be edited before the form is cleared
				if(response.responseText)
					{	
					//alert(response.text);
					// closes the loading wheel visual
					//$("#loadingWheel").fadeTo("medium", 0); 

					success("Successfully Saved.", lead_id);
					
					// sets buttons back enabled
					$that.find("input[type='submit']").attr("value", btnText);
                  	$that.find("input[type='submit']").removeAttr('disabled');
					//alertResponse(response);
					}
					
				else
					{fail("An error has occurred, please try again or notify SDR", lead_id);
					// sets buttons back enabled
					$that.find("input[type='submit']").attr("value", btnText);
                  	$that.find("input[type='submit']").removeAttr('disabled');
					alertResponse(response);
					}
				}
			
			});
	return false;
	
	}); // end listeners
}); // end function



















///////////////////////////////////////////////////////
////////////// Utility Functions
////////////////////////////////////////////////////


//////////////////////////////////////////
///////// this function is used to clean filenames when uploading an image or file.
///////// it mimics a php function in the imageUpload library, this is the client side mirror of it
////////////////////////////////////////

function cleanFileName(filename)
	{
	var illegal_chars = new Array('`', '~', '!', '@', '#', '$', '%', '^', '&', '=', '_', '*', '(', ')', '+', '[', '{', ']', '}', '|', ';', ':', "'", '"', ',', '<', '>', '/', '?', ' ');
		
	for (var i=0; i<illegal_chars.length; i++) 
		{
		var q = new RegExp('\\'+illegal_chars[i],"g");
		filename = filename.replace(q, '-');
		}

	//alert(filename)
	return filename;	
	} // end cleanFileName function



//////////////////////////////////////////
// global success and fail message functions
// these could probably be improved but seem to work
//////////////////////////////////////////
// used in User Management page Salesforce.php
function success(msg, id)
	{
	if(id == undefined)
		{
		id = '';
		}
	$("#success"+id).empty();
	$("#success"+id).append(msg);
	$("#failBox"+id).css("display","none"); 
	$("#fail"+id).empty();
	$("#successBox"+id).css("display","block");
	$("#loadingWheel").fadeTo("medium", 0.0);	
	}

function fail(msg, id)
	{
	if(id == undefined)
		{
		id = '';
		}
	$("#fail"+id).empty();
	$("#fail"+id).append(msg);
	$("#successBox"+id).css("display","none"); 
	$("#success"+id).empty();
	$("#failBox"+id).css("display","block"); 
	$("#loadingWheel"+id).fadeTo("medium", 0.0);
	}
	
	
	
	
	
	
	
///////////////////////////////////
////// toggles the feedback form on/off the page
///////////////////////////////////
$(function(){
$('.toggle_feedback').click(function() {
	$("#website_feedback").toggle('fast');
	return false;
	});	
});




///////////////////////
////
//// This function is used for inserting text into a textarea at the cursor position
//// We utilize it in the email template creator
//// http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
////////////////////////

function insertAtCaret(areaId,text) { 
	var txtarea = document.getElementById(areaId); 
	var scrollPos = txtarea.scrollTop; 
	var strPos = 0; 
	var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) ); 
	
	if (br == "ie") 
		{ 
		txtarea.focus(); 
		var range = document.selection.createRange(); 
		range.moveStart ('character', -txtarea.value.length); 
		strPos = range.text.length; 
		} 
		
	else if (br == "ff") strPos = txtarea.selectionStart; 
	
	var front = (txtarea.value).substring(0,strPos); 
	var back = (txtarea.value).substring(strPos,txtarea.value.length); 
	txtarea.value=front+text+back; 
	strPos = strPos + text.length; 
	if (br == "ie") 
		{ 
		txtarea.focus(); 
		var range = document.selection.createRange(); 
		range.moveStart ('character', -txtarea.value.length); 
		range.moveStart ('character', strPos); 
		range.moveEnd ('character', 0); 
		range.select();
		} 
	else if (br == "ff") 
		{ 
		txtarea.selectionStart = strPos; 
		txtarea.selectionEnd = strPos; 
		txtarea.focus(); 
		} 
	txtarea.scrollTop = scrollPos; 
	
	//$("#txtarea").wysiwyg('setContent');

	} 


///////////////////
/// function just to get the email template subject, body..etc WITHOUT populating the vars
/// used specifically on the Email-Templates.php page 
///////////////////
$(function(){
	$("select.emailTemplateEditor").change(function(){
		//alert ($(this).attr('value'));
		
		//var selectId = $(this).attr('id');
		var template_id = $(this).attr('value');
		var idSplit = 1;
		var leadID = 1;
				
		// if templateID == 0 clear the form (means new email template)
		if (template_id == '0' || template_id == 0)
			{
			// clear form
			resetForm("emailTemplateForm");
			$('#template_id').attr('value', '0');
			
			return false;	
			}
		
			var response = $.ajax({
				type: "POST",
				url: domain+"Email-Templates.php",
				data: "action=get_unpopulated_template&template_id=" + template_id,
				error: function(){ fail("There has been an error retrieving the Email Template, please try again.  If problem persists please contact SDR.");
					//alertResponse(response);
				},
				success: function(del)
					{ 
					if(response.responseText)
						{
						//alert(response.responseText);
						
						var emailJSON = eval("(" + response.responseText + ")");
						var emailSubject = emailJSON.subject;
						var emailBody = emailJSON.tpl_source;
						var emailName = emailJSON.name;
						var is_archived = emailJSON.is_archived;
						var is_skin = emailJSON.is_skin;
						var emailId = emailJSON.template_id;
						//var emailSelected = emailJSON.selected;
						
						//alert(emailBody);
						//eval("(" + jsonData1 + ")")
						
						//alert(emailJSON.subject);
						$('#template_id').attr('value', emailId);
						$('#subject-'+leadID).attr('value', emailSubject);
	
						$('#templateName-'+leadID).attr('value', emailName);
						
						if(is_archived == 1)
							{
							$("#archived-1").attr("checked","checked");
							}
						else if(is_archived == 0)
							{
							$("#archived-0").attr("checked","checked");
							}
						
						if(is_skin == 1)
							{
							$("#is_skin-1").attr("checked","checked");
							}
						else if(is_skin == 0)
							{
							$("#is_skin-0").attr("checked","checked");
							}
						

						//$("input[name='radio_name']:checked").val();
						// populate textarea with response 
						$("#emailContent-"+leadID).val(emailBody);
	
						}
					else
						{
						alertResponse(response);
						}
					}
				
				});
		
		return false;

	});
}); // end function



//////////////////////////////////////////
///////// Reset Form ////////////////////
////////////////////////////////////////
function resetForm(id) {
	$('#'+id).each(function(){this.reset();}); 	
	}
