$.fn.preload = function() {
    this.each(function(){
        $("<images/>")[0].src = this;
    });
}

/* WYSIWYG */
		function insertImage(id,size) {
			$.get("/js/ajax/general/wysiwyg/insertImage.php", {
					"imageID" : id,
					"size" : size
				},
				function(data) {
					ProcessContent();
					myData = $("#editedText").val() + data;
					textContent.document.write(myData);
					$("#addImageForm").dialog("close");
			});
			
			event.preventDefault();
		}

		function reloadImageList(itemID) {
			$("#images").html("<img src=\"/images/loading.gif\" />");
			$.getJSON("/js/ajax/general/wysiwyg/reloadImageList.php", {
					"refer" : $("#refersTo").val()+"|"+itemID
				},
				function(data) {
					if(data) {
						$("#images").html("");
						$.each(data, function() {
							$("#images").append("<div id=\"imageInsertContainer\" value=\""+this.Image_ID+"\"><div id=\"imageThumbContainer\"><img src=\"/uploads/gallery/tiny_"+this.Image_Filename+"\" /></div><div class=\"insertImageName\"><input type=\"text\" name=\"insertImageNameField\" id=\"insertImageNameField\" value=\""+this.Image_Caption+"\" /></div><a href=\"#\" id=\"insertImage\"><div id=\"insertImageContainer\">Insert</div></a><div id=\"useInSlideshow\">Slideshow<input type=\"checkbox\" id=\"useInSlideshow\" class=\"useInSlideshow_"+this.Image_ID+"\" value=\""+this.Image_ID+"\" /></div><a href=\"#\" id=\"deleteImage\" onClick=\"deleteImage("+this.Image_ID+");\"><div id=\"deleteImageContainer\"><img src=\"/images/delete.png\" alt=\"Delete\" /></div></a></div>");
							if(this.Slideshow == 'Y') {
								$(".useInSlideshow_"+this.Image_ID).attr("checked","checked");
							}
						});
					}
			});
		}

		function def() {
		   document.getElementById("fonts").selectedIndex=0;
		   document.getElementById("size").selectedIndex=1;
		   document.getElementById("color").selectedIndex=0;
		}
		
		function fontEdit(x,y) {
		   textContent.document.execCommand(x,"",y);
		   textContent.focus();
		}

		function ProcessContent() {
		   var textContentText = textContent.document.body.innerHTML; 
		   $("#editedText").val(textContentText);
		} 

		function deleteImage(id) {
			if(confirm("Are you sure you wish to delete this? Deleting the image will not remove it from the text - you need to remove it there also.")) {
				$.get("/js/ajax/admin/gallery/deleteImage.php", {
						"id" : id
					},
					function(data) {
						reloadImageList($("#ID").val());
				});
			}
		}

		function doToggleView() { 
			var viewMode = $("#viewMode").val();
			if(viewMode == "1") { 
				var answer = confirm("Switching to the source mode is not recommended unless you have a knowledge of coding HTML. Click ok to proceed, or cancel to continue with the interactive editor");
				if(answer) {
					$("#toggleView").attr({
							title :"Switch to Interactive editing mode",
							value :"Interactive Editing mode"
							});

					iHTML = textContent.document.body.innerHTML; 

					textContent.document.body.innerText = iHTML; 

					/* Hide all controls */
					size.style.display = "none"; 
					color.style.display = "none";
					left.style.display = "none";
					center.style.display = "none";
					right.style.display = "none";
					outdent.style.display = "none";
					indent.style.display = "none";

					textContent.focus(); 

					viewMode = "2";
				}
			} 
			else { 
				$("#toggleView").attr({
						title :"Switch to Source editing mode",
						value :"View Source"
						});

				iText = textContent.document.body.innerText; 

				textContent.document.body.innerHTML = iText; 

				/* Show all controls */
				size.style.display = "inline"; 
				color.style.display = "inline";
				left.style.display = "inline";
				center.style.display = "inline";
				right.style.display = "inline";
				outdent.style.display = "inline";
				indent.style.display = "inline";

				viewMode = "1";
			}
			$("#viewMode").val(viewMode);
		}

		function changeContent() {
			var viewMode = $("#viewMode").val();
			if (viewMode == "2" ) {
				iText = textContent.document.body.innerText; 
				textContent.document.body.innerHTML = iText; 
			}
		} 
		
		function prompt() {
				// get field to be validated
				var inputForm = document.getElementById( 'inputModal' );
				inputForm.style.display = 'block';
			}

			function getPdata( arg ) {
				var inputForm = document.getElementById( 'inputModal' );
				if ( 'cancel' == arg ) {
				inputForm.style.display = 'none';	// hide form
				return;	// exit immediately
			}
			else {
				var n = f.name.value;
				var a = parseInt( f.age.value );
				inputForm.style.display = 'none';	// hide form
				ProcessContent();
				myData = $("#editedText").val() + "<a href = '" + linkPath + "'>" + linkTitle + "</a>";
				textContent.document.write(myData);
			}
		}
		
		function reloadSliderImages() {
			$.getJSON("/js/ajax/general/wysiwyg/getSliderDetails.php", {
				"refersTo" : $("#refersTo").val()+"|"+$("#ID").val()
				}, function(data) {
				$("#sliderImages").html(" ");
				if(data) {
					$.each(data, function() {
						$("#sliderImages").append("<span id=\"sliderID_"+this.Image_ID+"\"><img src=\"/uploads/slider/tiny_"+this.Image_Filename+"\" /><span class=\"editableCaption\">"+this.Image_Caption+"</span>  <span class=\"deleteSliderImage\">Delete</span></span><br />");
						/*if(this.Image_Caption.length < 1) {
							$("#sliderImages").append("</span></span><br />");
						}
						else {
							$("#sliderImages").append(this.Image_Caption + "</span></span><br />");
						}*/
					});
				}
				$('.editableCaption').inlineEdit({
					buttonText: 'Save Changes',
					save: function(e, data) {
						var imagesID = $(this).parent().attr("id");
						imagesID = imagesID.replace("sliderID_","");
	 
						$.get("/js/ajax/general/wysiwyg/captionEdit.php", {'userID' : "1", 'imageID' : imagesID, 'newCaption' : data.value});
					}
				});
				
			});
		}
		
/* END WYSIWYG */

/* Slider */
function runSlider() {
	$('#slider a').css({opacity: 0.0});
	
	$('#slider a:first').addClass('show').css({opacity: 1.0});
	
	$('#slider .sliderCaption').css({opacity: 0.7});

	$('#slider .sliderContent').html($('#slider a:first').find('img').attr('alt'));
	
	setInterval('sliderGallery()',6000);
}

function sliderGallery() {
	var current = ($('#slider a.show')?  $('#slider a.show') : $('#slider a:first'));

	var next = ((current.next().length) ? ((current.next().hasClass('sliderCaption'))? $('#slider a:first') :current.next()) : $('#slider a:first'));	
	
	var caption = next.find('img').attr('alt');	
	
	next.css({opacity: 0.0}).addClass('show').animate({opacity: 1.0}, 1000);

	current.animate({opacity: 0.0}, 1000).removeClass('show');
	
        if(caption != undefined) {
            $('#slider .sliderContent').css({opacity: 0.0}).html(caption).animate({opacity: 1.0}, 1000);
        }
}
/* END SLIDER */

$(function() {

	
	$("#emailSignature").focus(function() {
		$("#signatureHelp").show("slide", {}, 1000);
	});
	
	$("#emailSignature").blur(function() {
		$("#signatureHelp").hide("slide", {}, 1000);
	});
	
	$("#dateFormat").focus(function() {
		$("#dateHelp").show("slide", {}, 1000);
	});
	
	$("#dateFormat").blur(function() {
		$("#dateHelp").hide();
	});
	
	$("#timeFormat").focus(function() {
		$("#timeHelp").show("slide", {}, 1000);
	});
	
	$("#timeFormat").blur(function() {
		$("#timeHelp").hide();
	});
	
	/* WYSIWYG */
		if($("#textEditor").length != 0) {
			var display = $("#textEditorSettings").val();
			
			var str = "<input type=\"hidden\" name=\"selectedImageInsert\" id=\"selectedImageInsert\" /><script type=\"text/javascript\" src=\"/js/jquery.inlineEdit.js\"></script><input type=\"hidden\" id=\"editedText\" name=\"editedText\" /><div id=\"textEditorOptions\"><div id=\"editorButtons\"><div id=\"textOptions\">";
			
			if(display == "all" || display.match("text") != null) {
				str = str+"<input type=\"button\" value=\"B\" id=\"bold\" onClick=\"fontEdit('bold')\" title=\"Bold\" /><input type=\"button\" value=\"I\" id=\"italic\" onClick=\"fontEdit('italic')\" title=\"Italics\" /><input type=\"button\" value=\"U\" id=\"underline\" onClick=\"fontEdit('underline')\" title=\"Underline\" />";
			}
			if(display == "all" || display.match("align") != null) {
				str = str+"<input type=\"button\" id=\"left\" onClick=\"fontEdit('justifyleft')\" title=\"Align Left\" /><input type=\"button\" id=\"center\" onClick=\"fontEdit('justifycenter')\" title=\"Align Center\" /><input type=\"button\" id=\"right\" onClick=\"fontEdit('justifyright')\" title=\"Align Right\" /><input type=\"button\" id =\"indent\" onClick=\"fontEdit('indent')\" title=\"Indent\" /><input type=\"button\" id=\"outdent\" onClick=\"fontEdit('outdent')\" title=\"Outdent\" />";
			}
			str = str+"<br /></div><div id=\"fontOptions\">";
			if(display == "all" || display.match("font") != null) {
				str = str+"<select title=\"Font Size\" id=\"size\" onChange=\"fontEdit('fontsize',this[this.selectedIndex].value)\"><option value=\"1\">X-Small 10pt</option><option value=\"2\">Small 11pt</option> <option value=\"3\" selected=\"selected\">Normal 13.5pt</option><option value=\"4\">Large 18pt</option><option value=\"5\">X-Large 24pt</option></select><select title=\"Text Colour\" id=\"color\" onChange=\"fontEdit('ForeColor',this[this.selectedIndex].value)\"><option value=\"black\">Black</option><option value=\"red\">Red</option><option value=\"blue\">Blue</option><option value=\"green\">Green</option><option value=\"pink\">Pink</option></select>";
			}
			if(display == "all" || display.match("list") != null) {
				str = str+"<input type=\"button\" id=\"numbers\" onClick=\"fontEdit('insertorderedlist')\" title=\"Numbered List\" /><input type=\"button\" id=\"bullet\" onClick=\"fontEdit('insertunorderedlist')\" title=\"Bullets List\" />";
			}	
			str = str+"</div><div id=\"otherButtons\">";
			if(display == "all" || display.match("other") != null) {
				str = str+"<input type=\"button\" id=\"image\" value=\"Image\" title=\"Add Image\" /><input type=\"button\" id=\"addLink\" value=\"Add Link\" onClick=\"insertLink()\" title=\"Add Link\" /><input type=\"button\" id=\"toggleView\" value=\"View Source\" onClick=\"doToggleView()\" title=\"Switch to Source editing mode\" /><input type=\"button\" id=\"toggleSlider\" value=\"Slider Control\" title=\"Control the sliders on the page\" /></div>";
			}
			str = str+"</div></div></div><iframe name=\"textContent\" id=\"textContent\"></iframe><br /><input type=\"hidden\" id=\"viewMode\" value=\"1\" />";

			
			if(display == "all" || display.match("other") != null) {
				str = str+"<link href=\"/js/uploadify/uploadify.css\" type=\"text/css\" rel=\"stylesheet\" /><script type=\"text/javascript\" src=\"/js/uploadify/swfobject.js\"></script><script type=\"text/javascript\" src=\"/js/uploadify/jquery.uploadify.v2.1.4.min.js\"></script><div id=\"addImageForm\" style=\"display:none;\"><form><input type=\"file\" name=\"uploadImage\" id=\"uploadImage\" /></form><div id=\"images\"></div></div><div id=\"sliderForm\" style=\"display:none;\"></div><div id=\"linkForm\" style=\"display:none;\"></div></div>";
			}
			
			$("#textEditor").html(str);
			
			textContent.document.designMode="on";
			textContent.document.open();
			textContent.document.write("Enter content here");
			textContent.document.close();
			
			/* Lets add the links! */
			
			$("#addLink").click(function() {
				$("#linkForm").html("<form><label for=\"linkTitle\">Link Title:&nbsp;</label><input type=\"text\" name=\"linkTitle\" id=\"linkTitle\" /><br /><label for=\"linkUrl\">Link URL:&nbsp;</label><input type=\"text\" name=\"linkURL\" id=\"linkURL\" /></form>");
				
				$("#linkForm").dialog({
					autoOpen: true,
					modal: false,
					buttons: {
						"Add Link" : function() {
							ProcessContent();
							myData = "<a href = '" + $("#linkURL").val() + "'>" + $("#linkTitle").val() + "</a>";
							textContent.document.open;
							textContent.document.write(previousData + myData);
							$(this).dialog("close");
						},
						"Close" : function() {
							$(this).dialog("close");
						}
					},
					close: function() {
					
					}
				});		
				event.preventDefault;
			});
			
			/* Handle the slider */
			$("#toggleSlider").click(function() {
				$("#sliderForm").html("<form><input type=\"file\" name=\"uploadSliderImage\" id=\"uploadSliderImage\" /></form><div id=\"sliderImages\"></div>");
				
				reloadSliderImages();
				
				$("#sliderForm").dialog({
					autoOpen: true,
					modal: false,
					buttons: {
						"Add Slider": function() {
							ProcessContent();
							myData = $("#editedText").val() + "{Slider}";
							textContent.document.write(myData);
							$(this).dialog("close");
						},
						"Save and Close" : function() {
							$(this).dialog("close");
						}
					},
					close: function() {
					
					}
				});

				$("#uploadSliderImage").uploadify({
					'uploader' : '/js/uploadify/uploadify.swf',
					'script'    : '/js/ajax/general/wysiwyg/sliderImageUpload.php',
					'cancelImg' : '/js/uploadify/cancel.png',
					'folder'    : '/uploads/slider',
					'auto'      : true,
					'multi' 	: true,
					'scriptData': { 'param1' : $("#refersTo").val()+"|"+$("#ID").val(), 'userID' : "<?=$_SESSION['user_id']; ?>" },
					'onComplete' : function(event, ID, fileObj, response, data) {
						reloadSliderImages();
					}
				});
		
				event.preventDefault;
			});
			
			/* Adding image */
			$("#image").click(function() {
				$("#addImageForm").html("<form><input type=\"file\" name=\"uploadImage\" id=\"uploadImage\" /></form><div id=\"images\"></div>");
			
				$("#addImageForm").dialog({
					autoOpen: true,
					modal: false,
					width: 322,
					buttons: {
						"Add Slideshow": function() {
							ProcessContent();
							myData = $("#editedText").val() + "{Slideshow}";
							textContent.document.write(myData);
							$(this).dialog("close");
						},
						"Save and Close": function() {
							$(this).dialog("close");
						}
					},
					close: function() {
						var selectednumbers = []
						$('#useInSlideshow:checked').each(function() {
							selectednumbers.push($(this).val());
						});

						if(selectednumbers.length == 0) { 
							selectednumbers = "none"; 
						}
						else {
							selectednumbers = selectednumbers.join("|");
						}
						
						$.get("/js/ajax/general/wysiwyg/updateSlideshow.php", {
								'slideshow' : selectednumbers,
								'refer' : $("#refersTo").val()+"|"+$("#ID").val()
							}).complete(function() {
							$(this).dialog("close");
						});
					}
				});
				
				$("#uploadImage").uploadify({
					'uploader' : '/js/uploadify/uploadify.swf',
					'script'    : '/js/uploadify/uploadify.php',
					'cancelImg' : '/js/uploadify/cancel.png',
					'folder'    : '/uploads/gallery',
					'auto'      : true,
					'multi' 	: true,
					'scriptData': { 'param1' : $("#refersTo").val()+"|"+$("#ID").val(), 'userID' : "<?=$_SESSION['user_id']; ?>" },
					'onComplete' : function(event, ID, fileObj, response, data) {
						reloadImageList($("#ID").val());
					}
				});
				
				reloadImageList($("#ID").val());
				
				event.preventDefault();
			});
			
			$("body").delegate(".deleteSliderImage", "click", function() {
				var thisID = $(this).parent().attr("id");
					
				$.get("/js/ajax/general/wysiwyg/deleteFromSlider.php", { 'imageID' : thisID.replace("sliderID_","") }).success(function() { $('#'+thisID).remove() });
			});
			
			$("body").delegate("#insertImage", "click", function() {
				$("#selectedImageInsert").val($(this).parent().attr("value"));
				$("#insertSettings").remove().delay(500);
				$(this).parent().after("<div id=\"insertSettings\"><div id=\"insertImageSizeTitle\">Size</div><div id=\"insertImageSizeText\"><img src=\"/images/wysiwygButtons/insertImageSmall.png\" alt=\"small\"/></div> <div id=\"insertImageSizeText\"><img src=\"/images/wysiwygButtons/insertImageMedium.png\" alt=\"medium\" /></div> <div id=\"insertImageSizeText\"><img src=\"/images/wysiwygButtons/insertImageLarge.png\" alt=\"large\" /></div><div id=\"radioPadding\"></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImageSize\" id=\"insertImageSize\" value=\"small\" /></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImageSize\" id=\"insertImageSize\" value=\"medium\" /></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImageSize\" id=\"insertImageSize\" value=\"large\" /></div><div class=\"clear\"></div><div id=\"insertImageAlignTitle\">Align</div><div id=\"insertImageSizePosition\"><img src=\"/images/wysiwygButtons/insertImageLeft.png\" alt=\"left\" /></div><div id=\"insertImageSizePosition\"><img src=\"/images/wysiwygButtons/insertImageCentre.png\" alt=\"center\" /></div><div id=\"insertImageSizePosition\"><img src=\"/images/wysiwygButtons/insertImageRight.png\" alt=\"right\" /></div><div id=\"radioPadding\"></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImagePosition\" id=\"insertImagePosition\" value=\"left\" /></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImagePosition\" id=\"insertImagePosition\" value=\"center\" /></div><div id=\"radioPadding\"><input type=\"radio\" name=\"insertImagePosition\" id=\"insertImagePosition\" value=\"right\" /></div><div class=\"clear\"></div><button id=\"insertImageNow\">Insert Image</button></div>");
				
				return false;
			});
			
			$("body").delegate("#insertImageSizeText", "click", function() {
				var thisValue = $(this).find('img').attr('alt');
				
				$("#insertImageSize[value="+thisValue.toLowerCase()+"]").attr("checked","checked");
			});
			
			$("body").delegate("#insertImageSizePosition", "click", function() {
				var thisValue = $(this).find('img').attr('alt');
				
				$("#insertImagePosition[value="+thisValue.toLowerCase()+"]").attr("checked","checked");
			});
			
			$("body").delegate("#insertImageNow","click", function() {
				$.get("/js/ajax/general/wysiwyg/insertImage.php", {
						"imageID" : $("#selectedImageInsert").val(),
						"size" : $("#insertImageSize:checked").val(),
						"align" : $("#insertImagePosition:checked").val()
					},
					function(data) {
						ProcessContent();
						var myData = $("#editedText").val() + data;
						textContent.document.open();
						textContent.document.write(myData);
						$("#addImageForm").dialog("close");
				});
				
				return false;
			});
                        
                        $("body").delegate("#insertImageNameField", "blur", function() {
                           var id = $(this).parent().parent().attr("value");
                           var textContent = $(this).val();
                           $.get("/js/ajax/general/wysiwyg/updateGalleryImageCaption.php", { "id" : id, "caption" : textContent });
                        });
		}
	/* END WYSIWYG */

	$("#addForm").append("<input type=\"reset\" id=\"button\" value=\"Reset Form\" />");

	var pathname = window.location.pathname;
	var hostname = window.location.hostname;

	if(pathname.indexOf("admin",0) > 0) {
		var text = $("#siteName").html();
		$("#siteName").html("<a href=\"http://" + hostname + "/admin/\" title=\"Return to Admin Home\" >" + text + "</a>");
		
		var text = $("#siteBanner").html();
		$("#siteBanner").html("<a href=\"http://" + hostname + "/admin/\" title=\"Return to Admin Home\" >" + text + "</a>");
	}
	else if(pathname.indexOf("admin",0) < 0) {
		var text = $("#siteName").html();
		$("#siteName").html("<a href=\"http://" + hostname + "/\" title=\"Return to Home\" >" + text + "</a>");
		
		var text = $("#siteBanner").html();
		$("#siteBanner").html("<a href=\"http://" + hostname + "/\" title=\"Return to Home\" >" + text + "</a>");	
	}
	
	if(pathname.indexOf("admin",0) > 0) {
		$("#settingsToggle").click(function() {
			if($("#settingsContainerBox").css("margin-left") == "-300px") {
				$("#settingsContainerBox").animate({marginLeft: "0px"}, 750);
				$("#settingsToggle").animate({marginLeft: "299px"}, 750);
			} 
			else if($("#settingsContainerBox").css("margin-left") == "0px") {
				$("#settingsContainerBox").animate({marginLeft: "-300px"}, 750);
				$("#settingsToggle").animate({marginLeft: "-1px"}, 750);
			}
		});

		$("#formContainerTitle").click(function(event) {
			event.preventDefault();
			$("#formContainerBox").slideToggle();
		});
		
		$("#formContainerBox a").click(function(event) {
			event.preventDefault();
			resetForm();
		});
	}
	
	if($("#runPageSlideshow").length) {
		$.getScript("/js/zingSlideshow.js", function() {
			$("#runPageSlideshow").zingSlideshow({
				timeout: 2000
			});
		});
	}
	
	$("body").delegate("img[src$='delete.png']", "mouseenter", function() {
		$(this).attr("src","/images/deleteHover.png");
	}); 
	
	$("body").delegate("img[src$='delete.png']", "mouseleave", function() {
		$(this).attr("src","/images/delete.png");
	});
	
	/* Make the cool highlighted navbar thingymajig */
	var path = location.pathname.substring(1) + location.search;
	if (path) {
		if(path.indexOf("admin/") != -1) {
			if(path == "admin/") {
				$('a[href="http://'+location.host+'/admin/"]').parent().addClass('selected');
			}
			else {
				if($('a[href$="'+path+'"]').parent().attr("class") == "dropDown") {
					$('a[href$="'+path+'"]').parent().addClass('selected');
				}
				else {
					$('a[href$="' + path + '"]').parent().parent().parent(".dropDown").addClass('selected');
				}
			}
		}
	}
	
	if($("#slider").length !== 0) {
		runSlider();
	}
	
    /*
      Add toggle switch after each checkbox.  If checked, then toggle the switch.
    */
    $('.toggleBox').after(function(){
		if ($(this).is(":checked")) {
			return "<a href='#' class='toggle checked' ref='"+$(this).attr("id")+"'></a>";
		}
		else{
			return "<a href='#' class='toggle' ref='"+$(this).attr("id")+"'></a>";
		}
    });
     
     /*
      When the toggle switch is clicked, check off / de-select the associated checkbox
     */
    $('.toggle').click(function(e) {
       var checkboxID = $(this).attr("ref");
       var checkbox = $('#'+checkboxID);

       if (checkbox.is(":checked")) {
         checkbox.removeAttr("checked");

       }else{
         checkbox.attr("checked","true");
       }
       $(this).toggleClass("checked");

       e.preventDefault();

    });
	
});
