(function ($) {
	$.toolkit = {
		external: function (options) {
			var defaults = {
				selector: 'a'
			};
			if (typeof options === 'string') defaults.selector = options;
			var options, hostname; 
			options= $.extend(defaults, options);
			hostname = window.location.hostname;
			hostname = hostname.replace('www.', '').toLowerCase();
			return $(options.selector).each(function () {
				if ( $(this).attr('href') != undefined) {
					var href = $(this).attr('href').toLowerCase();
					if (href.indexOf('http://') != -1 && href.indexOf(hostname) == -1) {
						$(this).attr('target', '_blank');
						$(this).addClass('external');
					}
				}
			})
		},
		slider: function(options) {
			var defaults = {
				selector: '#slider',		
				prevId: 'prevBtn',
				prevText: 'Previous',
				nextId: 'nextBtn',	
				nextText: 'Next',
				controlsShow: false,
				controlsBefore: '',
				controlsAfter: '',	
				controlsFade: true,
				firstId: 'firstBtn',
				firstText: 'First',
				firstShow: false,
				lastId: 'lastBtn',	
				lastText: 'Last',
				lastShow: false,				
				vertical: false,
				speed: 1200,
				auto: true,
				pause: 4000,   
				continuous: true, 
				numeric: false,
				numericId: 'controls'
			}; 
			
			var options = $.extend(defaults, options);  
					
			$(options.selector).each(function() {
				var obj = $(this);
				var s = $("li", obj).length;
				var w = $("li", obj).width();
				var h = $("li", obj).height();
				var clickable = true;
				obj.width(w);
				obj.height(h);
				obj.css("overflow","hidden");
				var ts = s-1;
				var t = 0;
				$("ul", obj).css('width',s*w);
				
				if(options.continuous){
					$("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px"));
					$("ul", obj).append($("ul li:nth-child(2)", obj).clone());
					$("ul", obj).css('width',(s+1)*w);
				}
				
				if (!options.vertical) { $("li", obj).css('float','left'); }
									
				if(options.controlsShow){
					var html = options.controlsBefore;				
					if(options.numeric){
						html += '<ol class="'+ options.numericId +'"></ol>';
					} else {
						if(options.firstShow) { html += '<span class="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>'; }
						html += ' <span class="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>';
						html += ' <span class="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>';
						if(options.lastShow) { html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>'; }
					}
					
					html += options.controlsAfter;						
					$(obj).after(html);										
				}
				
				if(options.numeric){									
					for(var i=0;i<s;i++){						
						$(document.createElement("li"))
							.attr('class', options.numericId + (i+1))
							.html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>')
							.appendTo($("."+ options.numericId))
							.click(function(){							
								animate($("a",$(this)).attr('rel'),true);
							});
					}							
				} else {
					$("a","."+options.nextId).click(function(){		
						animate("next",true);
					});
					$("a","."+options.prevId).click(function(){		
						animate("prev",true);				
					});	
					$("a","."+options.firstId).click(function(){		
						animate("first",true);
					});				
					$("a","."+options.lastId).click(function(){		
						animate("last",true);				
					});				
				}
				
				function setCurrent(i){
					i = parseInt(i, 10)+1;
					$("li", "." + options.numericId).removeClass("current");
					$("li." + options.numericId + i).addClass("current");
				}
				
				function adjust(){
					if(t>ts) { t=0; }
					if(t<0) { t=ts;	}
					if(!options.vertical) {
						$("ul",obj).css("margin-left",(t*w*-1));
					} else {
						$("ul",obj).css("margin-left",(t*h*-1));
					}
					clickable = true;
					if(options.numeric) { setCurrent(t); }
				}
				
				function animate(dir,clicked){
					if (clickable){
						clickable = false;
						var ot = t;				
						switch(dir){
							case "next":
								t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1;						
								break; 
							case "prev":
								t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1;
								break; 
							case "first":
								t = 0;
								break; 
							case "last":
								t = ts;
								break; 
							default:
								t = dir;
								break; 
						}
						var diff = Math.abs(ot-t);
						var speed = diff*options.speed;						
						if(!options.vertical) {
							p = (t*w*-1);
							$("ul",obj).animate(
								{ marginLeft: p }, 
								{ queue:false, duration:speed, complete:adjust }
							);
						} else {
							p = (t*h*-1);
							$("ul",obj).animate(
								{ marginTop: p }, 
								{ queue:false, duration:speed, complete:adjust }
							);
						}
						
						if(!options.continuous && options.controlsFade){					
							if(t==ts){
								$("a","."+options.nextId).addClass('inactive');
								$("a","."+options.lastId).addClass('inactive');
							} else {
								$("a","."+options.nextId).removeClass('inactive');
								$("a","."+options.lastId).removeClass('inactive');					
							}
							if(t===0){
								$("a","."+options.prevId).addClass('inactive');
								$("a","."+options.firstId).addClass('inactive');
							} else {
								$("a","."+options.prevId).removeClass('inactive');
								$("a","."+options.firstId).removeClass('inactive');
							}
						}
						
						if(clicked) { clearTimeout(timeout); }
						if(options.auto && dir=="next" && !clicked){
							timeout = setTimeout(function(){
								animate("next",false);
							},diff*options.speed+options.pause);
						}
				
					}
					
				}
				// init
				var timeout;
				if(options.auto){
					timeout = setTimeout(function(){
						animate("next",false);
					},options.pause);
				}
				
				if(options.numeric) { setCurrent(0); }
			
				if(!options.continuous && options.controlsFade){					
					$("a","."+options.prevId).addClass('inactive');
					$("a","."+options.firstId).addClass('inactive');				
				}
				
			});
		  
		},
		forms: function (options) {
			var defaults = {
				selector: 'form',
				errorClass: 'error',
				err: 'This is required',
				errEmail: 'A valid email address is required',
				errUrl: 'A valid URL is required',
				errPhone: 'A valid Phone number is required',
				errPhoneIE: 'A valid Irish Phone number is required',
				errNumber: 'This field requires a number with a maximum length of 4 numbers',
				errTwitter: 'A Valid Twitter name is required with @ and twitter name eg @corkartdesign',
				errFacebook: 'A Valid Facebook URL is required eg http://www.facebook.com/facebookname',
				errLinkedIn: 'A Valid LinkedIn URL is required eg http://www.linkedin.com/linkedinname',
				errCat: 'You need to  select at least one category',
				errCatDuplicate: 'You have selected the same category more than once',
				errPass: 'Passwords do not match',
				errPassLength: 'Password needs to be at least 5 characters',
				errOldPass: 'Please enter in your old Passowrd',
				errUserlength: 'Studio/ Organisation name needs to be at least 5 characters',
				errNoDefault: 'No Default Image has been selected, Please select a Default Image',
				errDefault: 'Too Many Default Image has been selected, Please select only 1 Default Image',
				errMaxLength: 'The maximum length for the image description is 80 characters.',
				errNoImage: 'No Image selected, Please select an Image or Delete the Row',
				errorMinLength: 'Minimum length is 3 characters',
				notValidClass: 'notvalid'
			};
			function check(obj) {
				if ($(obj).val() === '' || checkLabel(obj)) {
					var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : options.err;
					error(obj, errormsg);
				}
			}
			function checkRegEx(obj, type) {
				var regEx, err;
				switch (type) {
				case 'email':
					regEx = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
					err = options.errEmail;
					break;
				case 'url':
					regEx = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/])+)?(.com|.ie|.eu|.net|.org|.edu|.co.uk|.us|.fr|.biz|.name|.coop|.info)$/;
					err = options.errUrl;
					break;
				case 'phone':
					regEx = /^\s*\(?\s*\d{1,4}\s*\)?\s*[\d\s]{5,8}\s*$/;
					err = options.errPhone;
					break;				
				case 'number':
					regEx = /^\s*\(?\s*\d{1,4}\s*\)*$/;
					err = options.errNumber;
					break;								
				case 'twitter':
					regEx = /^@+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
					err = options.errTwitter;
					break;					
				case 'facebook':
					regEx = /^http:\/\/www.facebook.com\/+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
					err = options.errFacebook;
					break;				
				case 'linkedin':
					regEx = /^http:\/\/(www.linkedin.com|ie.linkedin.com)\/+(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
					err = options.errLinkedIn;
					break;									
				}	

				var val = $(obj).val();
				if (val === '' && $(obj).hasClass('not-required')){
				
				} else{
					val = $.trim(val);
					if (val.search(regEx) === -1 || checkLabel(obj)) {
						var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
					}
				}
			}

			function checkhttp(obj)
			{
				var check, httpval;
				httpval = $(obj).val();
				
				if (httpval === '' && $(obj).hasClass('not-required')) {
					//Do Nothing
				} else{
					if(httpval.match('^(http|https)://')){
				} else{
						$(obj).val('http://' + $(obj).val());
					}
				}
			}
			
			function checkPass(obj)
			{
				var pass, confirm;
				pass = $(obj).val();
				confirm = $('input.confirm').val();
					if(pass !== confirm)
				{
					err = options.errPass;
					var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
				}
			}
			
			function checkLength(obj)
			{
				var min, length;
				min = $(obj).attr('minlength');
				length = $(obj).val().length;
				if( min > length)
				{
					if(length === '')
					{
						//Do nothing as error already added
					}
					else{
						err = options.errPassLength;
						var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
					}
				}
			
			}

			function minLength(obj)
			{
				var min, length;
				min = $(obj).attr('minlength');
				length = $(obj).val().length;
				if( min > length)
				{
					if(length === '')
					{
						//Do nothing as error already added
					}
					else{
						err = options.errorMinLength;
						var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
					}
				}
			
			}
			
			function checkOldPassword(obj)
			{
				var old, pass, errormsg;
				
				old = $('input.old').val().length;
				pass = $(obj).val().length;
				
				if(pass > 0 && old === 0)
				{
					err = options.errOldPass;
					errormsg = ($('input.old').attr('title') !== '') ? $('input.old').attr('title') : err;
					error('input.old', errormsg);
				}
				else if(pass > 0 && old < 5)
				{
					err = options.errPassLength;
					errormsg = ($('input.old').attr('title') !== '') ? $('input.old').attr('title') : err;
					error('input.old', errormsg);
				}
			}
			
			function checkSelect(obj) {
				var select, select_2, select_3, errormsg;
				select = $(".cat-type option:selected").val(); 
				select2 = $(".cat-type-2 option:selected").val(); 
				select3 = $(".cat-type-3 option:selected").val(); 
				
				if((select === ""|| select === "N/A") && (select2 === ""|| select2 === "N/A") && (select3 === ""|| select3 === "N/A")){
					err = options.errCat;
					errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
					error(obj, errormsg);
				}
				
				/*Check if any select equal each other and that all values are not empty or N/A */ 
				else if (((select === select2) ||  (select === select3) || (select2 === select3)) && ((select !== "N/A") && (select2 !== "N/A") || (select3 !== "N/A"))){
					err = options.errCatDuplicate;
					errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
					error(obj, errormsg);
				}
			
			}
			
			function checkFacebook(obj) {
				var fbval;
				fbval = $(obj).val();
				
				if (fbval === '' && $(obj).hasClass('not-required')){
					//Do Nothing
				}else{
					if(fbval.match('^(http://www.facebook.com/)')){
					} else if(fbval.match('^(www.facebook.com/)')){
						$(obj).val('http://' + $(obj).val());
					}else {
						$(obj).val('http://www.facebook.com/' + $(obj).val());
					}
				}
			
			
			}			
			
			function checkLinkedIn(obj) {
				var linkedin;
				linkedin = $(obj).val();
				
				if (linkedin === '' && $(obj).hasClass('not-required'))
				{
					//Do Nothing
				}
				else
				{
					if(linkedin.match('^(http://www.linkedin.com/|http://ie.linkedin.com/)')){
					} else if(linkedin.match('^(www.linkedin.com/)')){
						$(obj).val('http://' + $(obj).val());
					} else {
						$(obj).val('http://ie.linkedin.com/pub/' + $(obj).val());
					}
				}
			
			
			}
			
			function checkDefault(obj) {
			var check, errormsg;
			check = $(".default:checked").length;	
					if(check === 0)
					{
						err = options.errNoDefault;
						errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
					}
	
					
					else if (check >= 2)
					{
						err = options.errDefault;
						errormsg = ($('tr.matrix-first td.matrix-last label').attr('title') !== '') ? $('tr.matrix-first td.matrix-last label').attr('title') : err;
						error('tr.matrix-first td.matrix-last label', errormsg);
					} else{
					}	
			}
			
			function checkImage(obj)
			{
				var image , disabled;
				$check = $(obj).hasClass("disabled");
				if ($check == false) 
				{
					$image= $(obj).val();
					if($image === ''){
						err = options.errNoImage;
						var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
						error(obj, errormsg);
					}
				}
				else {}
			}
			
			function checkLabel(obj) {
				var text = $('label[for=' + $(obj).attr('id') + ']').text();
				return (text == $(obj).val());
			}
			
			function checkMaxLength(obj) {
				var errormsg, max, length;
				max = 80;
				length = $(obj).val().length;
				
				if( length > max)
				{
					err = options.errMaxLength;
					var errormsg = ($(obj).attr('title') !== '') ? $(obj).attr('title') : err;
					error(obj, errormsg);
				}
				
			}
			
			function error(obj, errormsg) {
				var parent = $(obj).parent();
				parent.append('<span class="'+options.errorClass+'">' + errormsg + '</span>');
				$('span.'+options.errorClass, parent).hide().fadeIn('fast');
				$(obj).addClass(options.notValidClass);
				valid = false;
			}
			$('input.label,textarea.label').each(function () {
				var text = $('label[for=' + $(this).attr('id') + ']').text();
				$('label[for=' + $(this).attr('id') + ']').css('display', 'none');
				$(this).val(text);
				$(this).focus(function () {
					if ($(this).val() === text) { $(this).val(''); }
				});
				$(this).blur(function () {
					if ($(this).val() === '') { $(this).val(text); }
				});
			});
			if (typeof options === 'string') { defaults.selector = options; }
			var options = $.extend(defaults, options);
			return $(options.selector).each(function () {
				$(this).submit(function () {
					$('.'+options.errorClass, this).remove();
					$('.' + options.notValidClass, this).removeClass(options.notValidClass);
					valid = true;
					$(':text.required', this).each(function () {
						if ($(this).hasClass('email')) {
							checkRegEx(this, 'email');
						} else if ($(this).hasClass('url')) {
							checkhttp(this);
							checkRegEx(this, 'url');
						} else if ($(this).hasClass('phone')) {
							checkRegEx(this, 'phone');
						} else if ($(this).hasClass('number')) {
							checkRegEx(this, 'number');
						}
						else if ($(this).hasClass('minlength')) {
							minLength(this);
						} else {
							check(this);
						}
					});				
					
					$(':text.not-required', this).each(function () {
						if ($(this).hasClass('email')) {
							checkRegEx(this, 'email');
						} else if ($(this).hasClass('url')) {
							checkhttp(this);
							checkRegEx(this, 'url');
						} else if ($(this).hasClass('phone')) {
							checkRegEx(this, 'phone');
						} else if ($(this).hasClass('number')) {
							checkRegEx(this, 'number');
						} else if ($(this).hasClass('twitter')) {
							checkRegEx(this, 'twitter');
						} else if ($(this).hasClass('facebook')) {
							checkFacebook(this);
							checkRegEx(this, 'facebook');
						} else if ($(this).hasClass('linkedin')) {
							checkLinkedIn(this);
						} else {
							check(this);
						}
					});	
					$(':password.required', this).each(function () {
						check(this);
					});					
					
					$(':password.password', this).each(function () {
						checkPass(this);
						checkLength(this);
					});					
					
					$(':password.new-password', this).each(function () {
						checkPass(this);
						checkLength(this);
						checkOldPassword(this);
					});
					
					$('select.required', this).each(function () {
						if ( $('option:selected', this) ) {
							check(this);
						}
					});					
					
					$('select.multiple', this).each(function () {
						if ( $('option:selected', this) ) {
							checkSelect(this);
						}
					});					
					$('textarea.required', this).each(function () {
						check(this);
					});					
					
					$('textarea.maxlength', this).each(function () {
						checkMaxLength(this);
					});
					$(':checkbox.required', this).each(function () {
						if (!$(this).attr('checked')) {
							var errormsg = ($(this).attr('title') !== '') ? $(this).attr('title') : options.err;
							error(this, errormsg);
						}
					});
					
					$(':radio', this).each(function () {
						checkDefault(this);					
					});					
					
					$(':file.required', this).each(function () {
						checkImage(this);				
					});
					
					if (valid === false) {
						var error_message_text = 'There were errors while attempting to update your account, please scroll up to fix the errors and submit again.';
						$('#form-errors').text(error_message_text).fadeIn();
						$('html, body').animate({scrollTop:$(options.selector).offset().top - 30}, 'slow');
					}
					
					return valid;
				});
			});
		}
	};
})(jQuery);

$(document).ready(function(){

	if($('#content').hasClass('edit-form')){	
	//if(false){
		//Gallery Validation
		$('td.matrix textarea').addClass('required maxlength');
		$('td.matrix input:radio').addClass('default');
		$('tr.matrix-first td.matrix-last input').addClass('first');
		$('.js_hide input:file').addClass('disabled');
		$('input:file').addClass('required file');
		
		//Add Validation when a new Row is created
		$('.matrix-add').live('click', function(){
			$('td.matrix textarea').addClass('required maxlength');
			$('td.matrix input:radio').addClass('default');
			$('.js_hide input:file').addClass('disabled');
			$('input:file').addClass('required file');
		});		
		
		$(".safecracker_file_set").each(function (i) {
			if ($('.safecracker_file_set:eq('+ i + ') .safecracker_file_thumb').length) { 			
				console.log('There is an image element');
			} else {
				$('.safecracker_file_set:eq(' + i + ')').append('<span class="error">Image has not uploaded. Please make sure the filesize is less than 500Kb</span>');
				console.log('No img elements found');
			}
		});
		
		
		$('#instructions li:nth-child(even)').addClass('even');
		
		$('.hidetext').live('click', function(e) { 
			if ($("#instructions li:first").is(":hidden")) {
				$("#instructions").slideDown();
				$('.hidetext').html('Hide Instructions');
			} else {
				$("#instructions").slideUp();
				$('.hidetext').html('Show Instructions');
			}
			e.preventDefault();
		});
		

	}
	$.toolkit.external();
	$.toolkit.forms({errorClass: 'error'});
	$.toolkit.slider();
	$("#tweets").tweet({
		join_text: "auto",
        count: 5,
        username: "corkartdesign",
        loading_text: "loading tweets..."
      });
});
