// google analytics
var _gaq = [];

// site vars
var site = {
	statics: 'static'
};

function s_preload() {
	$('body').append(
		'<div id="preload" class="n-vhidden">'
			+ '<div class="ui-loadmask"></div>'
			+ '<div class="n-loader-large-snake"></div>'
		+ '</div>');
}

function s_tips_forms($w) {
	$w.find('table.n-thtml').closest('form').formtips();
}

function s_focus_forms($w) {
	var $i = $w.find('form.n-cform, form.n-eform, form.n-sform, form.n-vform');
	$i = $i.find('input,select,textarea,button');
	$i = $i.not(':hidden,:disabled,[readonly]').eq(0);
	if ($i.length > 0) {
		$i.focus();
		$('body').scrollTop(0).scrollLeft(0);
	}
}

function s_hook_forms($w) {
	$w.find('form[hooked!=true]').each(function() {
		var $t = $(this);
		$t.attr('hooked', 'true');
		if (this.target == '' || this.target == '_self'
			|| this.target == '_top' || this.target == '_parent') {
			$t.submit(s_submit);
		}
	});
}

function s_hack_forms($w) {
	if ($.browser.msie && $.browser.majorVersion < 7) {
		var onclick = function() {
			var t = this;
			$(this).closest('form').find('input[type=submit],button').each(function() {
				if (this != t) {
					this.disabled = true;
				}
			});
		};
		
		$w.find('form[hacked!=true]')
			.find('button[type=submit]').each(function() {
				if (!this.onclick) {
					$(this).click(onclick);
				}
			}).end()
			.attr('hacked', 'true');
	}
}

function s_submit() {
	var form = this, 
		$f = $(this), 
		$b = $(this).closest('.popup, .inner'),
		lm = ($f.height() > 20 && $f.attr('loadmask') != 'false');
	if ($b.length > 0) {
		setTimeout(function() {
			var data = $f.serializeArray();
			if ($b.hasClass('inner')) {
				data.push({ name: '__inner', value: 'true' });
			}
			else {
				data.push({ name: '__popup', value: 'true' });
			}
			if (lm) {
				$b.parent().loadmask();
			}
			$.get(form.action, data, function(html) {
				$b.parent().unloadmask().html(html);
			}, 'html');
		}, 10);
		return false;
	}
	else {
		if (lm) {
			$f.loadmask();
		}
		return true;
	}
}

function sl_sort(id, el) {
	var co = el.value.split(' ');
	if (co.length == 2) {
		$('#' + id + '_so_c').val(co[0]);
		$('#' + id + '_so_d').val(co[1]);
		sl_submit(id);
	}
}
function sl_sorta(id, name, dir) {
	sl_sortn(id, name, dir.toUpperCase() == "ASC" ? "DESC" : "ASC");
}
function sl_sortn(id, name, dir) {
	$('#' + id + '_so_c').val(name);
	$('#' + id + '_so_d').val(dir);
	sl_submit(id);
}
function sl_goto(id, s) {
	$('#' + id + '_pg_s').val(s);
	sl_submit(id);
}
function sl_limit(id, el) {
	$('#' + id + '_pg_l').val(el.value);
	sl_submit(id);
}
function sl_submit(id) {
	var $form = $('#' + id);
	var $pi = $form.closest('.inner');
	if ($pi.size() > 0) {
		var data = $form.serializeArray();
		data[data.length] = { name: '__inner', value: 'true' };
		
		$pi.parent()
			.loadmask({ cssClass: 'n-loader-large-snake' })
			.load($form.attr('action'), data, function() {
				$pi.parent().unloadmask();
			});
	}
	else {
		s_loadmask();
		$form.submit();
	}
}

function s_loadmask() {
	$('body').loadmask({
		cssClass: 'n-loader-large-snake',
		mask: false,
		window: true
	});
}
function s_resize() {
	$(window).trigger('resize');
}

function s_getLinkMark() {
	var i = location.href.lastIndexOf('#');
	if (i > 0) {
		return location.href.substring(i);
	}
	else {
		return "";
	}
}

function s_setTitle(title) {
	var d = document.title.indexOf(' - ');
	if (d >= 0) {
		document.title = title + document.title.substring(d);
	}
	else {
		document.title = title;
	}
}

function s_setTheme(theme) {
	if (!theme) {
		theme = $.cookie("ui-theme");
		if (!theme) {
			return;
		}
	}

	var link = $("link.ui-theme");
	if (link.size() > 0) {
		var href = link.first().attr('href');
		var i = href.indexOf("themes");
		if (i > 0) {
			href = href.substring(0, i) + "themes/" + theme + "/jquery-ui.css";
		}
		link.last().after('<link class="ui-theme" href="' + href + '" rel="stylesheet" type="text/css" media="all"/>');
		if (link.size() > 3) {
			link.first().remove();
		}
	}

	var bcs = $('body').prop('className').split(' ');
	var bc = '';
	for (var i = 0; i < bcs.length; i++) {
		var s = bcs[i].trim();
		if (s != '' && !s.startsWith('ui-theme-')) {
			bc += s + ' ';
		}
	}
	bc += ' ui-theme-' + theme;

	$('body').prop('className', bc);
	$.cookie("ui-theme", theme);

	if (window.frames && window.frames.length > 0) {
		for (var i = 0; i < window.frames.length; i++) {
			try {
				if (window.frames[i].s_setTheme) {
					window.frames[i].s_setTheme(theme);
				}
			}
			catch (ex) {
			}
		}
	}
}
function s_setLang(v) {
	var u = location.href, i = u.indexOf('?');
	if (i > 0) {
		var qs = $.param(u.queryParams('__locale'));
		u = u.substring(0, i);
		if (qs.length > 0) {
			location.href = u + '?' + qs + '&__locale=' + v;
			return;
		}
	}
	location.href = u + '?__locale=' + v;
}

function s_decorate_tools($w) {
	$w.find('.xhead').addClass('ui-state-default');

	$w.find('.stoggle')
		.mouseenter(function() {
			$(this).addClass('ui-state-highlight');
		})
		.mouseleave(function() {
			$(this).removeClass('ui-state-highlight');
		});

	$w.find('.menu')
		.mouseover(function(evt) {
			if (evt.target.tagName == 'A') {
				$(evt.target).addClass("ui-state-hover").css('border', '0 none');
			};
		})
		.mouseout(function(evt) {
			if (evt.target.tagName == 'A') {
				$(evt.target).removeClass("ui-state-hover").css('border', '0 none');
			};
		});

	$w.find('.collapse[decorated!=true]')
		.attr('decorated', 'true')
		.each(function() {
			var $eh = $(this);
			var $eb = $eh.next();
			$eh.css('cursor', 'pointer')
				.prepend('<span class=\"n-fright ui-icon ui-icon-triangle-1-'
					+ ($eb.is(':hidden') ? 'e' : 's') + '\"></span>')
				.click(function() {
					var $eh = $(this);
					var $eb = $eh.next();
					if ($eb.is(":hidden")) {
						$eb.slideDown();
						$eh.children(".ui-icon")
							.removeClass("ui-icon-triangle-1-e")
							.addClass("ui-icon-triangle-1-s");
					}
					else {
						$eb.slideUp();
						$eh.children(".ui-icon")
							.removeClass("ui-icon-triangle-1-s")
							.addClass("ui-icon-triangle-1-e");
					}
				});
		});
}

function s_icon(i) {
	return '<img src="' + site.blank + '" class="' + i + '"/>';
}

function s_decorate_side($w) {
	var cc = { path: site.base + '/' };
	var ca = $.jcookie('s-ui-side');
	var $c = $w.find('#content');

	var h = ($.browser.msie && $.browser.majorVersion < 7) ? 'height' : 'min-height';
	var mh = parseInt($c.css(h));
	function ch($s) {
		$c.css(h, mh > $s.height() ? mh : $s.height());
	}

	$w.find("#side_left, #side_right").each(function() {
		var $s = $(this);
		ch($s);

		var id = this.id;
		var d = id.replace('side_', '');
		var sideable = $s.attr('sideable') != "false";
		var stateful = $s.attr('stateful') != "false";

		$s.find('.n-sect[decorated!=true]')
			.attr('decorated', 'true')
			.each(function() {
				var $es = $(this);
				var $eh = $es.find('.n-sect-head').each(s_decoreate_section_head_icon);
				var $eb = $es.children('.n-sect-body');
				if (sideable && $eh.size() > 0 && $eh.size() > 0) {
					var $ev = $eh.clone().appendTo($es).css({
						display: 'none'
					});
					var hidden = $eb.is(":hidden");
					if (id && stateful) {
						hidden = ca[id];
					}
					if (hidden) {
						$eb.hide();
						$eh.hide();
						$ev.show();
						$s.addClass('side-' + d + '-vert');
						$c.addClass('has-' + d + '-vert');
						ch($s);
					}
					$eh.css({
							'cursor': 'pointer'
						})
						.prepend($('<em class=\"ui-icon ui-icon-triangle-1-w n-side-toggler"></em>'))
						.mouseenter(function() {
							$(this).addClass("n-sect-head-hover");
						})
						.mouseleave(function() {
							$(this).removeClass("n-sect-head-hover");
						})
						.click(function() {
							$es.hide('slide', { direction: d }, function() {
								$eb.hide();
								$eh.hide();
								$ev.show();
								$es.show('slide', { direction: d }, function() {
									$s.addClass('side-' + d + '-vert');
									$c.addClass('has-' + d + '-vert');
									ch($s);
									s_resize();
								});
								if (id && stateful) {
									var ca = $.jcookie('s-ui-side');
									ca[id] = "hidden";
									$.jcookie('s-ui-side', ca, cc);
								}
							});
						});
					$ev.removeClass('n-sect-head')
						.addClass('n-sect-vert ui-widget-content ui-corner-all')
						.css({
							'cursor': 'pointer'
						})
						.append('<img src="' + site.blank + '" class=\"ui-icon ui-icon-triangle-1-e"/>')
						.click(function() {
							$es.hide('slide', { direction: d }, function() {
								$ev.hide();
								$eb.show();
								$eh.show();
								$s.removeClass('side-' + d + '-vert');
								$('#content').removeClass('has-' + d + '-vert');
								$es.show('slide', { direction: d }, function() {
									ch($s);
									s_resize();
								});
								if (id && stateful) {
									var ca = $.jcookie('s-ui-side');
									delete ca[id];
									$.jcookie('s-ui-side', ca, cc);
								}
							});
						});
					$ev.each(function() {
						var $et = $(this).find('.n-sect-title');
						$et.html($et.text().split('').join('<br/>'));
					});
				}
			});
	});
}

function s_decorate_navi($w) {
	$w.find('.navi li').each(function() {
		var $li = $(this).css('border', '0 none');
		if ($li.hasClass('active')) {
			$li.addClass('ui-state-active');
		}
		else {
			$li.addClass('ui-state-default');
		}
		$li.mouseenter(function() {
			$li.addClass('ui-state-highlight');
		}).mouseleave(function() {
			$li.removeClass('ui-state-highlight');
		});
	});
}

function s_decoreate_section_head_icon() {
	var $eh = $(this);
	var $ei = $eh.find('.n-sect-icon');
	if ($ei.size() > 0) {
		$eh.css('background-image', 'none');
	}
}

function s_decorate_section($w) {
	$w.find('.n-sect .n-sect-head').each(s_decoreate_section_head_icon);
}

function s_decorate_step($w) {
	$w.find('ul.n-step[decorated!=true]')
		.attr('decorated', 'true')
		.children('li').each(function() {
			var li = $(this);
	
			if (li.hasClass('n-step-arrow')) {
				li.html('<em class="ui-icon ui-icon-carat-1-e"></em>');
			}
			else if (li.hasClass('n-step-self')) {
				li.addClass('ui-state-highlight');
			}
			else {
				li.addClass('ui-state-default');
			}
		});
}

function s_decorate(selector) {
	$(selector).each(function() {
		var $w = $(this);
		if ($w.attr("decorated") != "true") {
			$w.attr("decorated", "true");
			s_decorate_section($w);
			s_decorate_tools($w);
			s_hook_forms($w);
		}
	});
}

function s_setbase(c) {
	var b = c.blank;

	c = $.extend(site, c);
	if (!b) {
		c.blank = c.statics + '/nuts/images/s.gif';
	}

	nuts.prompt.defaults.blankImg = c.blank;
	$.cookie.defaults = c.cookie;
	return site;
}

function s_main(c) {
	c = $.extend({ main: "#main, #admin" }, c);
	c = s_setbase(c);

	// document - onload
	$(function() {
		s_preload();
		
		var $w = $(c.main);
		if ($w.attr("decorated") != "true") {
			$w.attr("decorated", "true");

			s_decorate_navi($w);
			s_decorate_side($w);
			s_decorate_section($w.find("#content"));
			s_decorate_tools($w);
			s_decorate_step($w);
			s_tips_forms($w);
			s_hook_forms($w);
			s_focus_forms($w);
			s_hack_forms($w);
		}

		// google analytics
		if (c.ga_account) {
			_gaq.push(['_setAccount', c.ga_account]);
			if (c.ga_domain) {
				_gaq.push(['_setDomainName', c.ga_domain]);
			}
			_gaq.push(['_trackPageview']);
			
			var ga = document.createElement('script');
			ga.type = 'text/javascript';
			ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			$('body').append(ga);
		}
	});
}

//set default
s_setbase({
	base: '',
	cookie: { expires: 180 }
});

