$(function(){
	initGreenbox();
	initColRight();
	resizeText(0.75);
	gallery1 = $('div.flash').gallery({
		duration: 800,
		autoRotation: 5000,
		listOfSlides: 'ul.gallery > li',
		effect: 'fade'
	});

	$('a.link-popup').fancybox({
		'padding' : 0,
		'titleShow' : false,
		'onStart': function(){
			gallery1.stop();
		},
		'onClosed':function(){
			gallery1.play();
		}
	});
	
	$('.a_print_nm').click(function () {
		$('#print_nm').attr('src', $(this).attr('href'));
		return false;
	});
	
	/*** ESTATE ***/
	
	$('.estate .switchtoimg').click(function () {
		$('.estate .switchtoimg').removeClass('active');
		$(this).addClass('active');
		$('.estate .map_image').attr('src', $(this).closest('a').attr('href'));
		var newlink = $(this).closest('a').attr('href').match(/src=(.*?)&/i)[1];
		$('.lightbox', $(this).closest('div')).attr('href', newlink);
		return false;
	});
	
	/*** FASTIGHETSLISTA ***/
	
	$('#fastighetstable tr').mouseover(function () {
		$(this).css('background', '#eeeeee');
	}).mouseout(function () {
		$(this).css('background', 'none');
	});
	
	$('.showbyggnad').fancybox({
		'autoScale'	 	: false,
		'width'			: 240,
		'height'			: 500,
		'transitionIn'	: 'none',
		'transitionOut': 'none',
		'type'			: 'iframe'
	});
	
	$('.lightbox').fancybox();
	
	$(".flashvideo").click(function() {
		
		$.fancybox({
			'autoscale' 	: false,
			'transitionIn' : 'none',
			'transitionOut': 'none',
			'padding' 		: 0,
			'title'  		: this.title,
			'width'  		: 370,
			'height' 		: 301,
			'type'   		: 'swf',
			'href'   		: this.href,
			'swf'   			: { 'wmode':'transparent', 'allowfullscreen':'true' }
		});
		
		return false;
	});
	
	var _navHover = false, _selectFocus = false, _timerS = false;
	
	$('#nav > li').hover(function() {
		var s = $('select', $('#nav > li').not(this)).blur();
		if (s.length) s.parents('#nav > li').removeClass('hover');
		$(this).addClass('hover');
		var li = this;
		this.focused = true;
		$('select', this)
			.focus(function() { $(this).attr('focused', '1'); })
			.blur(function() { $(this).attr('focused', ''); if (!li.focused) $(li).removeClass('hover'); })
	},
	function() {
		var s = $('select[focused]', this);
		if (!s.length) $(this).removeClass('hover');
		this.focused = false;
	});

	$('select.lokal_url').change(function() {
		var val = $(this).val();
		if (val)
			location.href = val;
	});
		

});
function fancybox_open_select(select) {
	$.fancybox($(select).val(), {
		type: "iframe",
		width: 500,
		height: 300,
		showCloseButton: false
	});
	$(select).val('');
}

function initColRight() {
	$('#main div.col-right').each(function () {
		var url = '';
		var stadid;
		var select;
		var hold = $(this);
		var bluebox1 = hold.find('div.bluebox');
		var selectstad = hold.find('select.ajax-sel');
		var baseurl = $('div.bluebox div.formholder > form').attr('action'); //selectstad.find('option:eq(0)').attr('title');
		var box = hold.find('div.hidden-box');
		var ajaxSel = hold.find('select.ajax-sel');
		var autocomp = hold.find('input.autocomplete');
		
		function stadsAjax(url){
			if (!url.match(/&lang/ig))
				url += '&lang=' + lang_code;
				
			$.ajax({
				type: "GET",
				global: false,
				dataType: "html",
				url: url,
				success: function(data){
					var _this = $('div.bluebox div.formholder > form');
					box.find('select').remove();
					select = $(data);
					box.prepend(select);
					box.css('display', 'block');
					select.change(function () {
						if (select.val() != ''){
							//$.cookie('ni_adress', baseurl + '?adress=' + select.val());
							adressAjax(select.find('option[selected]').html(), select.val());
						}
						//else $.cookie('ni_adress', null);
					});
					
					if ($.cookie('ni_adress_id')) {
						adressAjax($.cookie('ni_adress'), $.cookie('ni_adress_id'));
					}

					//_this.submit(function(){
						//txtAjax(autocomp.val());
						//alert(autocomp.val());
						//return false
					//});
				},
				error:function(){
					alert('Ajax error!');
				}
			});
		}

		$('div.bluebox div.formholder > form').submit(function() {
			return false;
		});
//alert($.cookie('ni_stad_id'));
//alert(baseurl);

		autocomp.autocomplete({
			source: baseurl,
			delay: 1,
			select: function(event, ui) {
				//alert("Selected: " + ui.item.value + " aka " + ui.item.id);
				//alert(baseurl + '?adress=' + ui.item.id);
				if (ui.item.stad) {
					$.cookie('ni_stad', ui.item.stad);
					$.cookie('ni_stad_id', ui.item.stadsid);
				}

				adressAjax(ui.item.value, ui.item.id);
			}
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append( "<a><strong>" + item.label + "</strong> (" + item.bet + ")<br>" + item.stad + "</a>" )
				.appendTo( ul );
		};

		selectstad.change(function () {
			box.css('display', 'none');
			stadid = selectstad.find('option[selected]').attr('title');
			if (!stadid) {
				$.cookie('ni_stad', null);
				$.cookie('ni_stad_id', null);
				$.cookie('ni_adress_id', null);
			}
			else {
				$.cookie('ni_stad', selectstad.val());
				$.cookie('ni_stad_id', stadid);
				stadsAjax(baseurl + '?moid=' + stadid);
			}
		});
		
		function adressAjax(adress, adressid){
			$.cookie('ni_adress', adress);
			$.cookie('ni_adress_id', adressid);

			$.ajax({
				type: "GET",
				global: false,
				dataType: "html",
				url: baseurl + '?adress=' + adressid + '&lang=' + lang_code,
				success: function (data){
					//$.cookie('formData', null);
					hold.find('div.bluebox:eq(1)').remove();
					hold.append($(data));
					bluebox1.hide();
					hold.find('a.link1').click(function(){
						$.cookie('ni_stad', null);
						$.cookie('ni_stad_id', null);
						$.cookie('ni_adress_id', null);
						hold.find('div.bluebox:eq(1)').remove();
						bluebox1.show();
						return false;
					});
				},
				error:function(){
					alert('Ajax error!');
				}
			});
		}
		
		if ($.cookie('ni_adress_id')) {
			adressAjax($.cookie('ni_adress'), $.cookie('ni_adress_id'));
		}
		else if ($.cookie('ni_stad_url')){
			selectstad.val($.cookie('ni_stad'));
			stadsAjax($.cookie('ni_stad_url'));
		}
		
	});
}

function _initColRight(){
	$('#main div.col-right').each(function(){
		var hold = $(this);
		var bluebox1 = hold.find('div.bluebox');
		var ajaxSel = hold.find('select.ajax-sel');
		var option = ajaxSel.find('option');
		var autocomp = hold.find('input.autocomplete');
		var box = hold.find('div.hidden-box');
		var flag = true;
		var select;
		var first = true;
		
		if ($.cookie('select1') && $.cookie('url')){
			ajaxSel.val($.cookie('select1'));
			start($.cookie('url'));
			ajaxSel.change(function(){
				$.cookie('select1', ajaxSel.val());
				var url = ajaxSel.find('option[selected]').attr('title');
				$.cookie('url', url);
				start(url);
			});
		}
		else{
			ajaxSel.change(function(){
				$.cookie('select1', ajaxSel.val());
				var url = ajaxSel.find('option[selected]').attr('title');
				$.cookie('url', url);
				start(url);
			});
		}
		
		function start(url){
			if (url){
				$.ajax({
					type: "GET",
					global: false,
					dataType: "html",
					url: url,
					success: function(msg){
						box.find('select').remove();
						select = $(msg);
						box.prepend(select);
						var _this = $('div.bluebox div.formholder > form');
						if ($.cookie('select2')){
							if (first){
								select.val($.cookie('select2'));
								selAjax2();
								first = false;
							}
							select.change(function(){
								if (select.val() != select.find('option:eq(0)').val()){
									$.cookie('select2', select.val());
									selAjax2();
								}
								else $.cookie('select2', null);
							});
						}
						else{
							select.change(function(){
								if (select.val() != select.find('option:eq(0)').val()){
									$.cookie('select2', select.val());
									selAjax2();
								}
								else $.cookie('select2', null);
							});
						}
						function selAjax2(){
							$.ajax({
								type: "GET",
								global: false,
								dataType: "html",
								data: select.val(),
								url: _this.attr('action'),
								success: function(msg){
									$.cookie('formData', null);
									hold.find('div.bluebox:eq(1)').remove();
									hold.append($(msg));
									bluebox1.hide();
									hold.find('a.link1').click(function(){
										hold.find('div.bluebox:eq(1)').remove();
										bluebox1.show();
										return false;
									});
								},
								error:function(){
									alert('Ajax error!');
								}
							});
						}
						if (flag){
							$.ajax({
								type: "GET",
								global: false,
								dataType: "html",
								url: autocomp.attr('title'),
								success: function(msg){
									autocomp.attr('title', '');
									var availableTags = msg.split(/,\s+/);
									autocomp.autocomplete({
										source: availableTags,
										open: function(event, ui) {
											$('ul.ui-menu').width(autocomp.outerWidth(true)-6);
											if ($('ul.ui-menu').outerHeight(true) > 200){
												$('ul.ui-menu').height(200);
												$('ul.ui-menu > li').css({
													width: $('ul.ui-menu').outerWidth(true)-24
												});
											}
											autocomp.keydown(function(event, ui) {
												setTimeout(function(){
													$('ul.ui-menu').height('auto');
													if ($('ul.ui-menu').outerHeight(true) > 200) {
														$('ul.ui-menu').height(200);
														$('ul.ui-menu > li').css({width: $('ul.ui-menu').outerWidth(true)-24});
													}
													else $('ul.ui-menu > li').css({width: '100%'});
												}, 300);
											});
										}
									});
									if ($.cookie('formData')){
										autocomp.val($.cookie('formData'));
										txtAjax($.cookie('formData'));
										_this.submit(function(){
											txtAjax(autocomp.val());
											return false
										});
									}
									else{
										_this.submit(function(){
											txtAjax(autocomp.val());
											return false
										});
									}
									function txtAjax(ttt){
										$.ajax({
											type: "GET",
											global: false,
											dataType: "html",
											data: autocomp.val(),
											url: _this.attr('action'),
											success: function(msg){
												$.cookie('formData', autocomp.val());
												$.cookie('select2', null);
												hold.find('div.bluebox:eq(1)').remove();
												hold.append($(msg));
												bluebox1.hide();
												hold.find('a.link1').click(function(){
													hold.find('div.bluebox:eq(1)').remove();
													bluebox1.show();
													return false;
												});
											},
											error:function(){
												alert('Ajax error!');
											}
										});
									}
								},
								error:function(){
									alert('Ajax error!');
								}
							});
							box.show();
							flag = false;
						}
					},
					error:function(){
						alert('Ajax error!');
					}
				});
			}
		}
		
	});
}

function initGreenbox(){
	$('div.greenbox').each(function(){
		var hold = $(this);
		var link = hold.find('.open-btn');
		var input = hold.find('input[title]');
		var box, h;
		var ret = hold.find('div.cont');
		
		link.addClass('closed');

		var close_greenbox = function() {
				box.animate({height:0}, 500)
				link.addClass('closed');
		}
		input.keydown(function(ev) { // Hide on escape
			if (ev.which == 27) {
				close_greenbox();
			}
		});

		link.click(function(){
			/*
			if (link.hasClass('closed')){
			*/
			//alert(input.attr('src')+"s="+escape(input.val())+"&lang="+lang_code);
				$.ajax({
					type: "GET",
					global: false,
					dataType: "html",
					data: "s="+escape(input.val())+"&lang="+lang_code,
					url: input.attr('src'),
					success: function(msg){
						hold.find('div.boxeswrap').remove();
						ret.append($(msg));
						box = hold.find('div.boxeswrap');
						h = 242; //box.outerHeight(true);
						if (link.hasClass('closed')){
							box.css({height:0})
							box.animate({height:h}, 500)
							link.removeClass('closed')
						}
						$('.close', box).click(function() {
							close_greenbox();
								      $(this).hide();
								      return false;
						});
					},
					error:function(){
						alert('Ajax error! 001');
					}
				});
			/*
			}
			else{
			close_greenbox();
			}
			*/
			return false;
		});
	});
}

function resizeText(val){
	var def = $('body').css('font-size').substr(0, $('body').css('font-size').length-2)/10;
	var temp = def+val;
	$('.resize-text').find('a.resize').click(function(){
		var resize = $(this);
		if(resize.data('resize')){
			resize.data('resize',false).html(lang_str.big_text);
			$('body').css('font-size', def+'em');
		}
		else{
			resize.data('resize',true).html(lang_str.smal_text);
			$('body').css('font-size', temp+'em');
		}
		return false;
	});
}
(function($) {
	function Gallery(el, options) {
		this._hold = $(el);
		this.initOptions(options);
		this._timer = options.autoRotation;
		this._t;
		this.initialize();
	}
	
	$.fn.gallery = function(options) {
		return new Gallery(this.get(0), options);
	};
	
	Gallery.prototype = {
		initOptions: function(_obj){
			this.options = {
				duration: 700,
				slideElement: 1,
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.link-next, a.btn-next, a.next',
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',
				circle: true,
				direction: false,
				IE: false
			};
			for(key in _obj) this.options[key] = _obj[key];
		},
		initialize: function(){
			var _this = this;
			var _hold = _this._hold;
			var _speed = _this.options.duration;
			var _timer = _this.options.autoRotation;
			var _el = _hold.find(_this.options.listOfSlides);
			if (_this.options.effect) var _list = _el;
			else var _list = _el.parent();
			var _switcher = _hold.find(_this.options.switcher);
			var _next = _hold.find(_this.options.nextBtn);
			var _prev = _hold.find(_this.options.prevBtn);
			var _count = _el.index(_el.filter(':last'));
			var _w = _el.outerWidth(true);
			var _h = _el.outerHeight(true);
			if (_this.options.switcher) var _active = _switcher.index(_switcher.filter('.active:eq(0)'));
			else var _active = _el.index(_el.filter('.active:eq(0)'));
			if (_active < 0) _active = 0;
			var _last = _active;
			
			// Installation directions
			if (!_this.options.direction) {
				var _wrapHolderW = Math.ceil(_list.parent().width() / _w);
				if (((_wrapHolderW - 1) * _w + _w / 2) > _list.parent().width()) _wrapHolderW--;
			}
			else{
				var _wrapHolderW = Math.ceil(_list.parent().height()/_h);
				if (((_wrapHolderW-1)*_h + _h/2) > _list.parent().height()) _wrapHolderW--;
			}
			
			// Setting "fade" or "slide" effect
			if (!_this.options.effect) var rew = _count - _wrapHolderW + 1;
			else var rew = _count;
			if (!_this.options.effect) {
				if (!_this.options.direction) _list.css({marginLeft: -(_w * _active)})
				else _list.css({marginTop: -(_h * _active)})
			}
			else {
				_list.css({
					opacity: 0
				}).removeClass('active').eq(_active).addClass('active').css({
					opacity: 1
				}).css('opacity', 'auto');
				_switcher.removeClass('active').eq(_active).addClass('active');
			}
			
			// Disable or enable buttons "prev next"
			if (_this.options.disableBtn) {
				if (_count < _wrapHolderW) _next.addClass(_this.options.disableBtn);
				_prev.addClass(_this.options.disableBtn);
			}
			
			// Function to "fade"
			function fadeElement(){
				if ($.browser.msie && _this.options.IE){
					_list.eq(_last).css({opacity:0});
					_list.removeClass('active').eq(_active).addClass('active').css({opacity:'auto'});
				}
				else{
					_list.eq(_last).animate({opacity:0}, {queue:false, duration: _speed});
					_list.removeClass('active').eq(_active).addClass('active').animate({
						opacity:1
					}, {queue:false, duration: _speed, complete: function(){
						$(this).css('opacity','auto');
					}});
				}
				if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
				_last = _active;
			}
			
			// Function for "slide"
			function scrollEl(){
				if (!_this.options.direction) _list.animate({marginLeft: -(_w * _active)}, {queue:false, duration: _speed})
				else _list.animate({marginTop: -(_h * _active)}, {queue:false, duration: _speed})
				if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
			}
			function toPrepare(){
				if ((_active == rew) && _this.options.circle) _active = -_this.options.slideElement;
				for (var i = 0; i < _this.options.slideElement; i++){
					_active++;
					if (_active > rew) {
						_active--;
						if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
					}
				};
				if (_active == rew) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
				if (!_this.options.effect) scrollEl();
				else fadeElement();
			}
			_this._hold.bind('runTimer', function(){
				_this._t = setInterval(function(){
					toPrepare();
				}, _this._timer);
			});
			_next.click(function(){
				if(_this._t) clearTimeout(_this._t);
				if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.removeClass(_this.options.disableBtn);
				toPrepare();
				if (_this._timer) _this._hold.trigger('runTimer');
				return false;
			});
			_prev.click(function(){
				if(_this._t) clearTimeout(_this._t);
				if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.removeClass(_this.options.disableBtn);
				if ((_active == 0) && _this.options.circle) _active = rew + _this.options.slideElement;
				for (var i = 0; i < _this.options.slideElement; i++){
					_active--;
					if (_active < 0) {
						_active++;
						if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
					}
				};
				if (_active == 0) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
				if (!_this.options.effect) scrollEl();
				else fadeElement();
				if (_this._timer) _this._hold.trigger('runTimer');
				return false;
			});
			if (_this.options.switcher) _switcher.click(function(){
				_active = _switcher.index($(this));
				if(_this._t) clearTimeout(_this._t);
				if (!_this.options.effect) scrollEl();
				else fadeElement();
				if (_this._timer) _this._hold.trigger('runTimer');
				return false;
			});
			if (_this._timer) _this._hold.trigger('runTimer');
		},
		stop: function(){
			var _this = this;
			if (_this._t) clearTimeout(_this._t);
		},
		play: function(){
			var _this = this;
			if (_this._t) clearTimeout(_this._t);
			if (_this._timer) _this._hold.trigger('runTimer');
		}
	}
}(jQuery));

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

