
$(function () {
	$('textarea[maxlen], input[maxlen]').each(checklength);
	$('textarea[maxlen], input[maxlen]').keyup(checklength);
	$('input:not(.default)').keypress(function (e) { return e.which != 13; });
	//$('.area').sortable({ containment:'parent', handle:'div.menu', items:'div.block' });
});

function checklength() {
	var max = parseInt($(this).attr('maxlen'));
	if ($(this).val().length > max) {
		$(this).val($(this).val().substr(0, max));
	}
	$(this).parent().find('.charsRemaining').html('' + (max - $(this).val().length) + ' Characters Remaining');
}

function IsChecked(sender, args) {
	args.IsValid = $("#" + sender.id.replace(/_Check/, '')).attr("checked");
}

//-- CONFIRM --\\
$(function () {
	$('.confirm').each(function (i, e) {
		var name = $(e).attr('title');
		if (!name) name = $(e).attr('value');
		if (!name && $(e).children.length > 0) name = $(e).children(0).attr('alt');
		if (!name) name = $(e).html();
		e.handler = $(e).attr('onclick') ? eval($(e).attr('onclick')) : function() { eval($(e).attr('data-click')) };
		$(e).attr('onclick', null);
		$(e).unbind('click');
		$(e).click(function (event) {
			if (!confirm('Are you sure you want to ' + name + '?')) {
				event.stopPropagation();
				event.preventDefault();
				return false;
			}
			if (e.handler) return e.handler();
			return true;
		});
	});
});

$(function () {
	$('input:button[data-href]').click(function () { window.location = $(this).attr('data-href'); });
});

/* HOVER */
(function ($) {
	jQuery.fn.hoverClass = function (cls) {
		var o = $(this[0]);
		o.hover(
			function () { o.addClass(cls); },
			function () { o.removeClass(cls); }
		);
	};
})(jQuery);

//-- BLOCK HOVER --\\
$(function () {
	$("div.area").hover(
		function () { $(this).addClass("border"); },
		function () { $(this).removeClass("border"); }
	);
	$("div.block").hover(
		function () { $(this).children("div.blockmenu").show(); },
		function () { $(this).children("div.blockmenu").hide(); }
	);
});

/* EDIT AREA */
if (typeof editAreaLoader != "undefined") {
	(function ($) {
		jQuery.fn.editArea = function () {
			var o = $(this[0]);
			editAreaLoader.init({
				id: o.attr('id')	// id of the textarea to transform	
				, start_highlight: true
				, allow_resize: 'y'
				, allow_toggle: true
				, language: 'en'
				, syntax: 'html'
				, toolbar: 'search, go_to_line, |, undo, redo, |, select_font, |, syntax_selection, |, change_smooth_selection, highlight, reset_highlight, |, help'
				, syntax_selection_allow: 'css,html,js,php,python,vb,xml,c,cpp,sql,basic,pas'
				//		,is_multi_files: true
				//		,EA_load_callback: 'editAreaLoaded'
				, show_line_colors: true
			});
		}
	})(jQuery);
	$(function () { $('textarea.editArea').editArea(); });
}

/* SCALE */
(function ($) {
	jQuery.fn.scale = function (options) {
		return this.each(function () {
			var opts = jQuery.extend(jQuery.fn.scale.defaults, options);
			var e = $(this);

			var MaxWidth = opts.width;
			var MaxHeight = opts.height;
			var width = parseInt(e.width());
			var height = parseInt(e.height());
			var scaleFactor = 0;

			if (width > MaxWidth || height > MaxHeight) {
				if ((MaxHeight / height) > (MaxWidth / width)) {
					scaleFactor = MaxHeight / height;
				} else {
					scaleFactor = MaxWidth / width;
				}
			}

			if (width > MaxWidth && MaxWidth > 0) {
				scaleFactor = MaxWidth / width;
				width = width * scaleFactor;
				height = height * scaleFactor;
			}

			if (height > MaxHeight && MaxHeight > 0) {
				width = width / scaleFactor;
				height = height / scaleFactor;
				scaleFactor = MaxHeight / height;
				width = width * scaleFactor;
				height = height * scaleFactor;
			}

			e.hide();
			e.width(parseInt(width) + 'px');
			e.height(parseInt(height) + 'px');
			e.show();
		});
	}
})(jQuery);
jQuery.fn.scale.defaults = { height: 100, width: 100 };

(function ($) {
	jQuery.fn.scaleCrop = function (options) {
		return this.each(function () {
			var opts = jQuery.extend(jQuery.fn.scaleCrop.defaults, options);
			var e = $(this);
			var width = parseInt(e.width());
			var height = parseInt(e.height());
			e.hide();

			if (opts.height > 0) {
				var scaleFactor = opts.height / height;
				width = width * scaleFactor;
				height = height * scaleFactor;
			} else if (opts.width > 0) {
				var scaleFactor = opts.width / width;
				width = width * scaleFactor;
				height = height * scaleFactor;
			}

			if (width > opts.width) {
				var margin = '-' + parseInt((width - opts.width) / 2) + 'px';
				//e.css({ 'margin-left': margin });
			} else if (height > opts.height) {
				var margin = '-' + parseInt((height - opts.height) / 2) + 'px';
				//e.css({ 'margin-top': margin });
			}

			//e.width(parseInt(width) + 'px');
			e.height(parseInt(opts.height) + 'px');
			e.show();
		});
	}
})(jQuery);
jQuery.fn.scaleCrop.defaults = { height: 100, width: 100 };

//REF: http://digitalbush.com/projects/watermark-input-plugin/
(function ($) {
	var map = new Array();
	$.Watermark = {
		ShowAll: function () {
			for (var i = 0; i < map.length; i++) {
				if (map[i].obj.val() == "") {
					map[i].obj.val(map[i].text);
					map[i].obj.css("color", map[i].WatermarkColor);
				} else {
					map[i].obj.css("color", map[i].DefaultColor);
				}
			}
		},
		HideAll: function () {
			for (var i = 0; i < map.length; i++) {
				if (map[i].obj.val() == map[i].text)
					map[i].obj.val("");
			}
		}
	}

	$.fn.Watermark = function (text, color) {
		if (!color) color = "#aaa";
		return this.each(
			function () {
				var input = $(this);
				var vtext = text;
				if (!vtext) vtext = input.attr('title');

				var defaultColor = input.css("color");
				map[map.length] = { text: vtext, obj: input, DefaultColor: defaultColor, WatermarkColor: color };
				function clearMessage() {
					if (input.val() == vtext) input.val("");
					input.css("color", defaultColor);
				}

				function insertMessage() {
					if (input.val().length == 0 || input.val() == vtext) {
						input.val(vtext);
						input.css("color", color);
					} else
						input.css("color", defaultColor);
				}

				input.focus(clearMessage);
				input.blur(insertMessage);
				input.change(insertMessage);

				insertMessage();
			}
		);
	};
})(jQuery);
$(function () { $('input.watermark').Watermark(); });

/* ROTATE */
(function ($) {
	jQuery.fn.rotate = function () {
		return this.each(function () {
			var o = $(this);
			if (o.length == 1 && o[0].nodeName == "#document") return;
			var next = function (i) {
				var children = o.children();
				children.hide();
				if (i > children.length - 1) i = 0;
				children.eq(i).show();
				setTimeout(function () { next(i + 1); }, 7000);
			};
			next(Math.floor(Math.random() * o.children().length));
		});
	};
})(jQuery);
$(function () { $('.rotate').rotate(); });

/* DROPDOWNS */
if (jQuery.fn.hoverIntent != undefined) {
	$(function () {
		$('.dropdown > li').hoverIntent(function () { $('.dropdown ul').hide(); $('ul', $(this)).show(); }, function () { });
		$('.dropdown').hoverIntent(function () { }, function () { $('.dropdown ul').hide(); });
	});
}

/* VALIDATION */
$(function () {
	$('form.validate').submit(function () {
		var cancel = false;
		$('input.required, textarea.required').each(function () {
			var input = $(this);
			if (input.val() == '' || input.val() == input.attr('title')) {
				var msg = input.attr('title');
				if (msg == '') msg = input.attr('name');
				alert(msg + ' is required');
				cancel = true;
			}
			return !cancel;
		});
		return !cancel;
	});
});

/**
* A simple querystring parser.
* Example usage: var q = $.parseQuery(); q.foo returns "bar" if query contains "?foo=bar"; multiple values are added to an array. 
* Values are unescaped by default and plus signs replaced with spaces, or an alternate processing function can be passed in the params object .
* http://actingthemaggot.com/jquery
*
* Copyright (c) 2008 Michael Manning (http://actingthemaggot.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
**/
jQuery.extend({
	parseQuery: function (qs, options) {
		var q = (typeof qs === 'string' ? qs : window.location.search), o = { 'f': function (v) { return unescape(v).replace(/\+/g, ' '); } }, options = (typeof qs === 'object' && typeof options === 'undefined') ? qs : options, o = jQuery.extend({}, o, options), params = {};
		jQuery.each(q.match(/^\??(.*)$/)[1].split('&'), function (i, p) {
			p = p.split('=');
			p[1] = o.f(p[1]);
			params[p[0]] = params[p[0]] ? ((params[p[0]] instanceof Array) ? (params[p[0]].push(p[1]), params[p[0]]) : [params[p[0]], p[1]]) : p[1];
		});
		return params;
	}
});

jQuery.extend({
	center: function (width, height) {
		var maxWidth = 480, maxHeight = 340;
		if (document.all || document.layers) {
			maxWidth = screen.availWidth;
			maxHeight = screen.availHeight;
		}
		return { left: (maxWidth - width) / 2, top: (maxHeight - height) / 2 };
	}
});

/* ***** POPUP ***** */
(function ($) {
	jQuery.fn.createPopup = function (options) {
		return this.each(function () {
			var e = $(this);
			var opts = jQuery.extend(jQuery.fn.createPopup.defaults, options, $.parseQuery(e.attr('href')), { title: e.attr('title') });
			e.click(function () {
				var loc = $.center(opts.width, opts.height);
				window.open(e.attr('href'), null, "width=" + opts.width + ",height=" + opts.height + ",resizable=yes,scrollbars=yes,left=" + loc.left + ",top=" + loc.top);
				return false;
			});
		});
	};
	jQuery.extend({
		closePopup: function () {

		}
	});
})(jQuery);
jQuery.fn.createPopup.defaults = { width: 300, height: 450, title: 'Popup' };
$(function () {
	$('a.popup').createPopup();
});

(function ($) {
	jQuery.fn.visible = function (vis) {
		return this.each(function () {
			if (vis) $(this).show(); else $(this).hide();
		});
	};
})(jQuery);

if (jQuery.fn.uploadify) {
	$(function() {
		$('.uploadify').uploadify({
			'script': 'files',
			'onAllComplete': function (event, data) { window.location.reload() },
			'onError': function (event, ID, fileObj, errorObj) { alert(errorObj.type + ' Error: ' + errorObj.info); }
		});
	});
}

$(function () {
	if (jQuery.fn.datepicker) {
		$('input.DatePicker').datepicker({
			showOn: 'both'
		});
	}
	if (jQuery.fn.datetimepicker) {
		$('input.DateTimePicker').datetimepicker({
			showOn: 'both',
			ampm: true
		});
	}
});

