/* Site functions */
	var root = "/";
	var sitename = 'Adler and Allan';
	var tagline = 'Speed, service and environmental integrity';
/* HTML5 compatibility, for older IE6 browsers */
	document.createElement('header');
	document.createElement('footer');
	document.createElement('section');
	document.createElement('aside');
	document.createElement('nav');
	document.createElement('article');
	document.createElement('video');
	
	
	
	
	
/* Rich text editor */


var uploaded_image_target = ''; 
var element; 
var needsAspectRatio = 0; 
var cropped_image_folder = ''; 
var save_to_db = 0;
var how_to_handle_image = '';
var inline_upload_element = '';
var upload_file_invoked_by = '';
/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
/*						UPLOAD NEW IMAGE DIALOG				 */
/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
	function select_image(element) {
		$('#image_upload').dialog({
			buttons: {
				'Upload Image': function() { 
					var options = {
						data: { file_posted: 'new_img', folder: 'originals', ajax: 'true' },
						success: crop_chosen_image,
						url: root+'ajax/upload_image.php',
						type: 'post',
						clearForm: false,
						resetForm: false,
						beforeSubmit: function() {
							$(element).after('<div id="loading">Uploading Image...</div>');
						}
					};
					how_to_handle_image = 'insert-into-wysiwyg';
					needsAspectRatio = 0;
					cropped_image_folder = 'small';
					related_id = '<?php echo $blog_id; ?>';
					save_to_db = 0;
					image_type = 'blog';
					$('#image_upload').ajaxSubmit(options);
					return false;
				},
				Cancel: function() { 
					 $(this).dialog("close");
				}
			},
			modal: true,
			minWidth: '100',
			maxWidth: '300',
			resizable: false
		});
	}

/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
/*						CROP IMAGE DIALOG/FORM					 */
/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
	function crop_chosen_image(responseText) {	
		$('#image_upload').dialog("close");
		$('#loading').remove();
		$('#img_src').val(responseText);
		$('#img_preview').after('<img id=\'img_preview1\' />');
		$('#img_preview').remove(); $('.jcrop-tracker').remove(); $('.jcrop-holder').remove();
		$('#img_preview1').attr('id','img_preview'); $('#img_preview').attr('src',responseText);
		$('#img_preview').Jcrop({ onSelect: updateCoords, aspectRatio: needsAspectRatio});
		function updateCoords(c) {
			document.getElementById('x').value = c.x;
			document.getElementById('y').value = c.y;
			document.getElementById('x2').value = c.x2;
			document.getElementById('y2').value = c.y2;
			document.getElementById('w').value = c.w;
			document.getElementById('h').value = c.h;
		};
		
		$('#image_crop_dialog').dialog({
			buttons: {
				'Save Image': function() { 
					var options = {
						data: { 
							folder: cropped_image_folder, 
							ajax: 'true', 
							library_image_type: image_type,
							media_related_id: related_id,
							save_into_database: save_to_db
						},
						success: insert_image,
						url: root + 'ajax/save_cropped_image.php',
						type: 'post',
						clearForm: false,
						resetForm: false
					};
					$('#image_crop_dialog').ajaxSubmit(options); 
					$(this).dialog('close');
					//return false;
				},
				Cancel: function() { 
					var image = $('#img_src').val();
					$.ajax({
						url: root + "ajax/delete_image.php",
						data: 'image_path='+image+'&ajax=true'
					});
					$(this).dialog('close');
				}
			},
			modal: true,
			minWidth: '100',
			maxWidth: '300',
			resizable: false
		});
	}
	
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
	
/* //////////////////////////////////////// */
/* //////////////////////////////////////// */
/*			DEAL WITH CROPPED IMAGE		  */
/* //////////////////////////////////////// */
/* //////////////////////////////////////// */
	function insert_image(responseText) {
		if (how_to_handle_image == 'insert-into-wysiwyg') {
			var result_array = responseText.split('::');
				path = result_array[0];
				alt = result_array[1];
				
			var imgPath = trim(path);
				
			uploaded_image_target.insertHtml('<img src="'+imgPath+'" alt="'+alt+'" style="float: left; padding: 4px;" />'); 
		} 
	}
	
/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
/*					UPLOAD NEW FILE DIALOG				 		 */
/* ///////////////////////////////////////////////////////// */
/* ///////////////////////////////////////////////////////// */
	function upload_file() {
		$('#file_upload').dialog({
			buttons: {
				'Save File': function() { 
					media_type = $('#related_type').html();
					media_id = $('#related_id').html();
					var options = {
						data: { ajax: 'true', related_type: media_type, related_id: media_id },
						success: file_uploaded,
						url: '<?php echo $pth; ?>ajax/upload_file.php',
						type: 'post',
						clearForm: false,
						resetForm: false,
						beforeSubmit: function() {
							$('#new_file').after('<br /><div id="loading">Uploading Image...</div>');
						}
					};
					$('#file_upload').ajaxSubmit(options);
					return false;
				},
				Cancel: function() { $(this).dialog('close'); }
			},
			modal: true,
			minWidth: '100',
			maxWidth: '300',
			resizable: false
		});
	}
	
/* File uploaded successfully */
	function file_uploaded(responseText) { 
		upload_file_invoked_by.insertHtml(responseText); 
		$('#file_upload').dialog('close'); 
		$('ul#documents').append('<li>'+responseText+'</li>'); 
		return true; 
	}

/* Document ready functions */
	$(document).ready(function() { 
		$('.date').datepicker({
			dateFormat: 'dd/mm/yy',
			changeMonth: true,
			changeYear: true,
			showAnim: 'clip',
			onSelect: function(dateText, inst) {
				var date_bits = dateText.split('/');
				var day = date_bits[0]; var month = date_bits[1]; var year = date_bits[2];
				$(this).next('.db_date').val(year+'-'+month+'-'+day);
			}
		});
		$('.rich_text').wysiwyg({ // Turn all 'rich txt editors' into WYSIWYG instances
			initialContent: '', 
			css: root+'css/editor.css',
			controls: {
        		strikeThrough: { visible: false },
				underline: { visible: true },
				cut: { visible: true },
				copy: { visible: true },
				paste: { visible: true },
				h1: { visible: true },
				h2: { visible: true },
				h3: { visible: true },
				insertImage: { visible: false },
				superscript: { visible: false },
				subscript: { visible: false },
				indent  : { visible : true },
				outdent : { visible : true },
				undo : { visible : true },
				redo : { visible : true },
				html  : { visible: true },
				insertHorizontalRule : { visible : true },
				addImg: {
					visible: true,
					groupIndex: 6,
					tooltip: 'Insert an image at the current cursor-location. You will be given the option to crop the image before it is inserted',
					icon: root+'images/icons/filetypes/icon_jpeg.gif',
					exec: function() { 
						uploaded_image_target = this;
						select_image('#new_img');
					},
					className: 'addImg',
					custom: true
				},
				addDoc: {
					visible: false,
					groupIndex: 6,
					tooltip: 'Select a new document to be added into the text. This will add a link to the document in the text, as well as listing\
					this document (and any others for this entry) at the foot the entry. If you do not wish to have a link to the file within the \
					text, simply select delete it from the text',
					icon: root+'images/icons/filetypes/icon_pdf.gif',
					exec: function() { 
						upload_file_invoked_by = this;
						upload_file();
					},
					className: 'addFile',
					custom: true
				}
			} 
		});
		
		// Turn elements into jQuery tooltip instances. 
		$('.tooltip').tipTip({ defaultPosition: 'top' }); $('.wysiwyg ul.toolbar li').tipTip({ defaultPosition: 'top' });
	}); 



/* Code to be executed after page-load, using jQuery. Used for loading plugins into page + adding functionality */
$(document).ready(function() {
					   
						   
/* Create clickable sections for admin forms */
	$('form.admin #sections section fieldset').hide();
	$('form.admin #sections section:first-child fieldset').slideDown(1500);
	$("form.admin #sections section h1").click(function() { 
		$("form.admin #sections section h1").removeClass('active');
		$(this).addClass('active'); 
		$("form.admin #sections section h1:not(.active)").next('fieldset').slideUp();
		$(this).next("fieldset").slideToggle(300); 
	});
	
/* Add effect to social media icons on all pages */




// Hide all the tooltips
$(".social_icons li").each(function() {
   $("a strong", this).css("opacity", "0");
});
  
$(".social_icons li").hover(function() { // Mouse over
   $(this)
      .stop().fadeTo(500, 1)
      .siblings().stop().fadeTo(500, 0.2);
        
   $("a strong", this)
      .stop()
      .animate({
         opacity: 1,
         top: "-10px"
      }, 300);
     
}, function() { // Mouse out
   $(this)
      .stop().fadeTo(500, 1)
      .siblings().stop().fadeTo(500, 1);
     
   $("a strong", this)
      .stop()
      .animate({
         opacity: 0,
         top: "-1px"
      }, 300);
});


/* Any textual inputs with values on page load will replace a blank field with these values using JavaScript */
	$('.replaceinitialtext').each(function() {
		if ($(this).val() != '' && $(this).val() != ' ' && $(this).val() != null) {
			var default_value = $(this).val();
			$(this).focus(function(){
				if ($(this).val() == default_value){
					$(this).val('');
				}
			}).blur(function(){
				if ($(this).val() == ''){
					$(this).val(default_value);
				}
			});
		}
	});
	
/* Apply selectable to each UL element with the 'selectable' class */
	$('.selectable li input:checkbox').hide();
	$('.selectable li').click(function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			$(this).children('input:checkbox').attr('checked', false);
		} else { 
			$(this).addClass('selected');
			$(this).children('input:checkbox').attr('checked', true);
		}
	});
	
/* Apply toolbox on hover to relevant elements */
	$('.toolbox').hide(); $('.toolbox').children().not('em, p, span').hide(); // hide the toolbox and it's tools
	var tools = new Array('edit', 'delete'); // used to check for classes + show tools
	$('.apply_tools li').live({
		mouseenter: function() {
			$('.toolbox').appendTo(this); // append toolbox to current element, be it a document, a file or whatever (must be in a UL though!)
			var i = 0;
			while (i < tools.length)  { // loop through tools
				var tool = tools[i]; // current tool, e.g. edit
				if ($(this).parent().hasClass(tool)) { $('.toolbox'+' #'+tool).show(); } // show necessary tools
				i++;
			}
			$('.toolbox').fadeIn();
		},
		mouseleave: function() { $('.toolbox').hide(); $('.toolbox').children().not('em, p, span').hide(); }
	});
	
/* Automatically apply a datepicker to any field with a 'date' class */
	$('.date').datepicker({
		dateFormat: 'dd/mm/yy',
		//dateFormat: 'yy-mm-dd',
		changeMonth: true,
		changeYear: true,
		showAnim: 'clip',
		buttonImage: root+'images/icons/calendar.png'
	});
	


/* Apply tooltips (created from element title) where the element has a class of 'tooltip' */
	$('.tooltip').tipTip({ defaultPosition: 'top' }); //$('.wysiwyg ul.toolbar li').tipTip({ defaultPosition: 'top' });
});

/* Turn all sliders into nivoSlider objects */
	$(window).load(function() { 
							
	$("#accordion").show();
	$("#accordion").accordion({autoHeight: true, active: 0});
	$("#accordion").accordion( "resize" );
	$("#loadingdiv").hide();
	
	
	
	if($("#map_canvas1").length > 0)
	{
		ShowMeTheMap(1);
		
		$( "#accordion" ).bind( "accordionchange", function(event, ui) {
		  var mapsNo = $('#numberOfMaps').val();
		  var id = ui.newContent.find('input').val();
		  $(id).html('<p>Loading map...</p>');
		  ShowMeTheMap(id);
		});
	}
	
	$('.slider').nivoSlider();
	
	if($("#videoslider").length > 0)
	{
		$('#videoslider').anythingSlider({
					autoPlay            : true,
					delay               : 8000,
					resizeContents      : true,
					addWmodeToObject    : 'transparent',
					navigationFormatter : function(index, panel){ // Format navigation labels with text
						return "Video " + index;
					}
				});	
	
	}
	
	 });

/* Will generate a slug from a value. Generally used to generate URL slug from a title onChange() */
	function generate_slug(value) { return value.toLowerCase().replace(/-+/g, '').replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, ''); }

/* Add a new category for selection */
	function add_new_category(name, callback) {
		var slug = generate_slug(name);
		$.ajax({
			url: root+'ajax/add_new_category.php',
			data: 'name='+name+'&slug='+slug,
			type: 'POST',
			success: function(data) { // returns id of new category
				if (data!='failure') {
					var category = new Array();
					category['id']=jQuery.trim(data);
					category['name']=name;
					category['slug']=slug;
					if (callback && typeof(callback)==="function") { callback(category); }
					return category;
				} else { alert('Sorry, an error occurred. Please try again, or if this error persists, contact web@grafika-uk.com'); } 
			}
		});
	}
	
	
/* Add a new video */
function add_new_video() {
	$('#fileForm').dialog({
		resizable: false,
		modal: true
	});
}
	
	
/* Insert the a category into a list width an id of categories (should only be one per page or will insert into LAST) */
	function add_category_to_list(data) {
		$('ul#categories').append($('ul#categories li').last().clone(true, true)); // clone the last category
		var new_category = $('ul#categories li').last(); // get the new category
		$(new_category).find('span').text(data['name']); // change it's name
		$(new_category).find(':input').attr('id',data['id']); // change the id 
		$('ul#categories .remove').hide();
	}
	
/* AJAX delete. Expects the id and type of the content to be deleted. It also allows for the specification of a callback */
	function ajax_delete(id, type, callback, args) {
		$.ajax({
			url: root+'ajax/delete.php',
			type: 'POST', 
			data: 'id='+id+'&type='+type,
			success: function(data) { 
			if (callback && typeof(callback) ==="function") { callback(args); } return true; }
		});
	}
	
/* AJAX toggle. Expects id and type of the content to be toggled. Also expects the field name to toggle. Toggles 1 to 0 and 0 to 1 */
	function ajax_toggle(id, type, callback, args) {
		$.ajax({
			url: root+'ajax/toggle.php', 
			data: 'id='+id+'&type='+type,
			success: function(data) { if (callback && typeof(callback)==="function") { callback(data, args); } return true; }
		});
	}
	
/* Remove table row - assumes a link within a TD within a TR is the value for ELEMENT */
	function remove_row(element) { $(element).parent().parent().fadeOut('slow'); }
	
/* Toggle an image based on it's current value */
	function toggle_active_image(status, element) {
		if (status==1) {
			$(element).attr('src', $(element).attr('src').replace('close.png', 'check.png'));
		} else {
			$(element).attr('src', $(element).attr('src').replace('check.png', 'close.png'));
		}
	}
	
/* Get the currently selected value of a radio button set*/	
	function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


