var s_conf = {};

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]').submit(s_submit).attr('hooked', 'true');
}

function s_hack_forms($w) {
	if ($.browser.msie && parseInt($.browser.version, 10) < 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.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 {
		$('body > div:first').loadmask({ mask: false, cssClass: 'n-loader-large-snake' });
		$form.submit();
	}
}

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();
		}
	}

	$.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').hover(function() {
		$(this).addClass('ui-state-highlight');
	}, function() {
		$(this).removeClass('ui-state-highlight');
	});

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

	$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="' + s_conf.blank + '" class="' + i + '"/>';
}

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

	var h = ($.browser.msie && (parseInt($.browser.version, 10) < 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-section[decorated!=true]')
			.attr('decorated', 'true')
			.each(function() {
				var $es = $(this);
				var $eh = $es.find('.n-section-head').each(s_decoreate_section_head_icon);
				var $eb = $es.children('.n-section-body');
				if (sideable) {
					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>'))
						.hover(function() {
								$(this).addClass("n-section-head-hover");
							}, function() {
								$(this).removeClass("n-section-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-section-head')
						.addClass('n-section-vert ui-widget-content ui-corner-all')
						.css({
							'cursor': 'pointer'
						})
						.append('<img src="' + s_conf.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-section-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.hover(function() {
			$li.addClass('ui-state-highlight');
		}, function() {
			$li.removeClass('ui-state-highlight');
		});
	});
}

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

function s_decorate_section($w) {
	$w.find('.n-section .n-section-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) {
	c.blank = c.base + '/static/nuts/images/s.gif';
	nuts.prompt.defaults.blankImg = c.blank;
	$.cookie.defaults = c.cookie;
	s_conf = c;
}

function s_main(c) {
	c = $.extend(s_conf, { main: "#main, #admin" }, 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);
		}
	});
}

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

