var CORE = function () {
	return {};
}();

// utils
CORE.Utils = function () {
	var that = arguments.callee.prototype;
	that.object = function (o) {
		function F(){};
		F.prototype = o;
		return new F();
	};
	that.extend = function (to, from) {
		var proto = that.object(from.prototype);
		proto.constructor = to;
		to.prototype = proto;
	};
	that.preloadImages = function (imgs) {
		var cache = [];
		for (var i = 0; i < imgs.length; i++) {
			var item = document.createElement('img');
			item.src = imgs[i];
			cache.push(item);
		}
	};
	that.isValueEmpty = function (val) {
		return !/[^ ]+/.test(val.toString());
	};
	that.isEmailValid = function (val) {
		return /^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z0-9._-]+)$/.test(val.toString());
	};
	that.fixButton = function (isValid, selector) {
		var isDisable = true;
		var opacity = 0.7;
		var button = $(selector);
		if (isValid) {
			isDisable = false;
			opacity = 1;
		}
		button.attr('disabled', isDisable).css('opacity', opacity);
	};
};

CORE.AjaxRotator = function () {
	var that = arguments.callee.prototype;
	var opts = (arguments[0].constructor == Object) ? arguments[0] : {};
	var contentSelector = (arguments[0].constructor == String) ? arguments[0] : opts.contentSelector;
	var navSelector = opts.navSelector;
	var index = 0;
	var delay = opts.delay || 5;
	var gallery = null;
	var zIndex = null;
	that.timer = null;
	var isMouseOver = false;
	opts = null;
	init();
	function init() {
		$(document).ready(function () {
			$('#subNavTwo').hide();
			$(navSelector).eq(index).addClass('active');
			gallery = $(contentSelector);
			that.mouseover();
		});
		$(window).load(function () {
			gallery.find('img:first').css('background', 'none');
			that.play();
		});
	}
	that.preload = function (imgs) {
		var cache = [];
		var i = imgs.length;
		while (i--) {
			var item = document.createElement('img');
			item.src = imgs[i];
			cache.unshift(item);
		}
	};
	that.mouseover = function () {
		$(navSelector).bind('mouseover', function () {
			var curLink = $(this);
			var curIndex = $(navSelector).index(curLink);
			if (curIndex != index) {
				that.show(curIndex, that.wait);
				$(navSelector).unbind('mouseover');
			}
		});
	};
	that.show = function (i, callback) {
		var url = $(navSelector).eq(i).attr('href');
		index = i;
		that.stop();
		$.ajax({
			type: 'POST',
			url: url,
			data: 'ajax=1',
			//dataType: 'json',
			timeout: 15 * 1000, // quit trying after 15 secs
			success: function (data) {
				var content = $(contentSelector);
				var nav = $(navSelector);
				try {
					nav.removeClass('active').eq(i).addClass('active');
					content.css({'z-index': zIndex}).fadeOut(1000);
					$('#content').append(data).find(contentSelector).eq(1).css({'z-index': zIndex + 1}).hide().fadeIn(1000, function () {
						content.remove();
						if (callback) callback();
						that.mouseover();
					});
					/*
						//content.replaceWith(data);
						$('#content').append(data).find(contentSelector).eq(1).css({'z-index': zIndex}).hide();
						nav.removeClass('active').eq(i).addClass('active');
						//window.location.hash = url;
						$(contentSelector).hide().fadeIn(500, function () {
							if (callback) callback();
							that.mouseover();
						});
					});
					*/
				} catch (e) {

				}
			},
			complete: function () {
				
			}
		});
	};
	that.nextIndex = function (i) {
		var num = $(navSelector).length;
		return (i < num - 1) ? i + 1 : 0;
	};
	that.play = function () {
		//window.location.hash = 'playing' + index;
		that.wait();
	};
	that.wait = function () {
		that.stop();
		if (!isMouseOver) {
			that.timer = setTimeout(function () {
				that.show(that.nextIndex(index), that.wait);
			}, delay * 1000);
		}
	};
	that.stop = function () {
		if (that.timer) clearTimeout(that.timer);
	};
};

CORE.Gallery = function () {
	var that = arguments.callee.prototype;
	var opts = (arguments[0].constructor == Object) ? arguments[0] : {};
	var selector = (arguments[0].constructor == String) ? arguments[0] : opts.selector;
	var index = 0;
	var delay = opts.delay || 5;
	var gallery = null;
	var zIndex = null;
	that.timer = null;
	var isMouseOver = false;
	opts = null;
	init();
	function init() {
		$(document).ready(function () {
			gallery = $(selector);
			var imgs = gallery.find('img').hide();
			zIndex = parseInt(imgs.eq(0).css('z-index')) || 0;
			imgs.hide().css('position', 'absolute').eq(0).show();
			//that.preload(imgs);
			gallery.hover(function () {
				isMouseOver = true;
				that.stop();
			}, function () {
				isMouseOver = false;
				that.play();
			});
		});
		$(window).load(function () {
			gallery.find('img:first').css('background', 'none');
			that.play();
		});
	}
	that.preload = function (imgs) {
		var cache = [];
		var i = imgs.length;
		while (i--) {
			var item = document.createElement('img');
			item.src = imgs[i];
			cache.unshift(item);
		}
	};
	that.show = function (i, callback) {
		that.stop();
		var curImg = gallery.find('img').eq(index);
		index = i;
		var curIndex = gallery.find('img').index(curImg);
		var timing = 100;
		if (curIndex != i) {
			curImg.css({'z-index': zIndex - 1}).fadeOut(timing);
		}
		gallery.find('img').eq(i).css({'z-index': zIndex}).fadeIn(timing, function () {
			if (callback) callback();
		});
		//window.location.hash = 'showing' + i;
	};
	that.nextIndex = function (i) {
		var num = gallery.find('img').length;
		return (i < num - 1) ? i + 1 : 0;
	};
	that.play = function () {
		//window.location.hash = 'playing' + index;
		that.show(index, that.wait);
	};
	that.wait = function () {
		that.stop();
		if (!isMouseOver) {
			that.timer = setTimeout(function () {
				that.show(that.nextIndex(index), that.wait);
			}, delay * 1000);
		}
	};
	that.stop = function () {
		if (that.timer) clearTimeout(that.timer);
	};
};

CORE.FormHandler = function (selector, successCallback) {
	var that = arguments.callee.prototype;
	var buttonSelector = selector + ' :input[type=submit], ' + selector + ' :input[type=image]';
	var errorClass = 'errors';
	var errorFieldClass = 'errorFld';
	var errorSummaryClass = 'errorSummary';
	var antibotFieldName = 'noErrors';
	var utils = {};
	init();
	function init() {
		$(document).ready(function () {
			utils = new CORE.Utils();
			$(selector).submit(function (e) {
				e.preventDefault();
				var frm = $(this);
				//if (frm.find(':input[name=' + antibotFieldName + ']').length == 0) {
					that.checkErrors(null, frm);
				//}
			});
			$(selector + ' :input[type!=submit]').blur(function (e) {
				var fld = $(this);
				that.checkErrors(fld, fld.closest('form'));
			});
		});
	}
	that.submit = function (frm) {
		var url = frm.attr('action');
		$.ajax({
			type: 'POST',
			url: url,
			data: 'ajax=1&' + antibotFieldName + '=true&' + frm.serialize(),
			dataType: 'json',
			timeout: 15 * 1000, // quit trying after 15 secs
			success: function (data) {
				if (data == true) {
					if (successCallback) successCallback();
				}
			},
			complete: function () {
				utils.fixButton(true, buttonSelector);
			}
		});
	};
	that.checkErrors = function (fld, frm) {
		var url = frm.attr('action');
		if (fld == null) { // submitting form, not just error check
			frm.find('.' + errorClass).remove();
			frm.find('.' + errorFieldClass).removeClass(errorFieldClass);
			frm.find(':input[name=' + antibotFieldName + ']').remove();
			frm.find('.errorMarker').html('&nbsp;');
			utils.fixButton(false, buttonSelector);
		} else {
			var row = fld.closest('.row');
			row.find('.' + errorClass).remove();
			row.find('.errorMarker').html('&nbsp;');
			fld.removeClass(errorFieldClass);
		}
		$.ajax({
			type: 'POST',
			url: url,
			data: 'ajax=1&' + frm.serialize(),
			dataType: 'json',
			timeout: 15 * 1000, // quit trying after 15 secs
			success: function (data) {
				var summaryFld = $('.' + errorSummaryClass);
				$('.success').remove();
				if (data != true) {
					var errors = data;
					var errorFieldName = null;
					var error = null;
					if (fld == null) { // check all fields
						for (var errorFieldName in errors) {
							showError(errors, errorFieldName);
							//summaryFld.find('ul').append('<li>' + data[errorFieldName] + '</li>');
						}
					} else { // check one field
						errorFieldName = fld.attr('name');
						showError(errors, errorFieldName);
					}
				} else if (fld == null) {
					that.submit(frm);
				}
			},
			complete: function () {
				utils.fixButton(true, buttonSelector);
			}
		});
		function showError(errors, errorFieldName) {
			var error = errors[errorFieldName];
			if (error) {
				//for (var i in error) {
					frm.find(':input[name=' + errorFieldName + ']').addClass(errorFieldClass).parent().find('.errorMarker').html('(' + error.toLowerCase() + ')');
					//break;
				//}
			}
		}
	};
};

CORE.Popup = function (selector, isCloseOnClickOut, closeCallback) {
	var that = arguments.callee.prototype;
	var popID = 'popup';
	var overlayID = 'pageOverlay';
	var body = $('body');
	var pop, overlay;
	var obj = $(selector);
	var url = obj.attr('href');
	var transitionTime = 0.2; // secs
	init();
	function init() {
		obj.click(function (e) {
			e.preventDefault();
			open();
		});
		$('#' + popID).find('.close').live('click', function (e) {
			e.preventDefault();
			that.close();
		});
		$(document).keyup(function(e) {
			if (e.keyCode == 27) { // esc
				that.close();
			}
		});
		$(window).bind('resize scroll', function () {
			position();
		});
	}
	function prepare() {
		$('#' + popID + ', #' + overlayID).remove();
		body.append('<div id="' + popID + '"></div><div id="' + overlayID + '"></div>');
		pop = $('#' + popID);
		overlay = $('#' + overlayID);
		overlay.css('opacity', 0.8);
		pop.hide();
		overlay.hide();
		overlay.click(function (e) {
			e.preventDefault();
			if (isCloseOnClickOut) that.close();
		});
	}
	function position() {
		if (pop) {
			var w = body.width();
			var h = $(document).height();
			var popW = pop.width();
			var popH = pop.height();
			pop.css({
				left: Math.floor($(window).scrollLeft() + ($(window).width() - popW) / 2) + 'px',
				top: Math.floor($(window).scrollTop() + ($(window).height() - popH) / 2) + 'px'
			});
			overlay.width(w);
			overlay.height(h);
		}
	}
	that.close = function () {
		pop = $('#' + popID);
		overlay = $('#' + overlayID);
		overlay.fadeOut(transitionTime * 1000);
		pop.fadeOut(transitionTime * 1000, function () {
			pop.remove();
			overlay.remove();
			if (closeCallback) closeCallback();
		});
	}
	function open() {
		prepare();
		position();
		overlay.fadeIn(transitionTime * 1000);
		pop.fadeIn(transitionTime * 1000);
		pop.append('<div class="preloader">loading...</div>');
		$.ajax({
			type: 'GET',
			url: url,
			data: 'ajax=1',
			error: function(xhr, status, error) {
				alert('Ajax error has occurred.');
				that.close();
			},
			success: function(data) {
				pop.html(data);
				position();
			},
			complete: function () {
				pop.find('.preloader').remove();
			}
		});
	}
};
