
var SYS = {};
var SITE = {};
var TABLES = {};
var FUNCTIONS = {};

/* EVENTHANDLER FOR DOMONLOAD
/* ADD FUNCTIONS THAT SHOULD RUN ON DOM LOAD
----------------------------------------------------*/
$(document).ready(function() {
    //##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##

    SYS.Init();
    SITE.Init();
    TABLES.Init();

    //##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>##
});

SYS.Init = function() {
    this.pageId = $('body').attr('id');
    this.pushResult = [];
   
    // Window settings
    this.winWidth = $(window).width();
    this.winHeight = $(window).height();
    this.docHeight = $(document).height();

    $(window).resize(function() {
        SYS.winWidth = $(window).width();
        SYS.winHeight = $(window).height();
        if ($('#fade').length > 0) FUNCTIONS.ModalUpdate();
    });

    // mouse coordinates
    this.mouseX = 0;
    this.mouseY = 0;

    // push area image auto swapper
    this.pushTimeout = 0;
    this.pushIdle = 12000;
    this.pushRunning = 6500;
    this.pushRunningCount = 0;

    // premise size slider settings
    this.sliderMinKvm = 0;
    this.sliderMaxKvm = 10000;
    this.sliderInterval1 = 300;
    this.sliderInterval2 = 3000;
    this.sliderStep = 1;
    // set the length of each interval in selector position units and the corresponding max values
    this.intervals = [{ len: SYS.sliderMaxKvm / 3, max: SYS.sliderInterval1, log: false }, { len: SYS.sliderMaxKvm / 3, max: SYS.sliderInterval2, log: true }, { len: SYS.sliderMaxKvm / 3, max: SYS.sliderMaxKvm, log: false}];
    // decide the rounding to use up to certain values
    this.rounding = [{ v: 300, r: 10 }, { v: 500, r: 20 }, { v: 1000, r: 50 }, { v: 3000, r: 100 }, { v: 10000, r: 500}];
    
    // premise search parms
    this.premiseMin = '';
    this.premiseMax = '';
    this.premiseDistrict = '';
    this.premiseSearchString = '';
    this.premiseType = '';
    this.premiseSearchAscending = true;
    this.premiseSearchSortBy = 0;
};

SITE.Init = function() {
  
    // if Cufon font replacement is defined
    if (window.Cufon) FUNCTIONS.FontReplace();
    SITE.Navigation();

    // enhanced forms
    $('fieldset').TextfieldPlaceholders();
    $('#content').FormSelectRestyled(true, 'form-drop-down', '--', 0);
    // check for push area
    if ($('#push').length > 0) FUNCTIONS.Push();
    if ($('#index', '#static').length > 0) FUNCTIONS.PushIndex();
    // check for AJAX search
    if ($('.ajax', '#index').length > 0) FUNCTIONS.AjaxSearch();
    if ($('.ajax', '#content').length > 0) FUNCTIONS.AjaxSearch();
    if ($('.ajax', '#subpage.building-page').length > 0) FUNCTIONS.ToggleBox($('#search-again'));
    // check for area slider
    var areaSlider = $('.area-slider', '#content');
    if (areaSlider) {
        FUNCTIONS.AreaSlider(areaSlider);
    }
    FUNCTIONS.ToolTip();
    FUNCTIONS.ImageCaption();
    FUNCTIONS.Share();
    FUNCTIONS.NewWin.init();
    
    // To trigger the right modal pop-up, pass the links title set as service name
    $('a[name=modal]').live('click', function() {
        FUNCTIONS.Modal($(this).attr('rel').toLowerCase(), $(this).parent().prevAll().length);
        return false;
    });
    
    // scroll page to anchor tag link
    $('a[href^="#"]').live('click', function(){
         var offset = $($(this).attr('href')).offset();
         $('html,body').animate({ scrollTop: offset.top }, 500);
         return false;
    });
 
 function sameHeightOnEachRowOnContactsPage(){
        var contactRows = $("body#subpage #content #contacts > div")
        .add("body#subpage #content #contacts > div > div");
        
        contactRows.each(function(){
            var contactRow = $(this);
            
            var name = contactRow.find("> dl.vcard > dt.name");
            
            name.equalizeHeights();
            
            var title = contactRow.find("> dl.vcard > dt.title");
            
            title.equalizeHeights();
        });
    }
    
    sameHeightOnEachRowOnContactsPage();
};
SITE.Navigation = function() {
    var dropDownParent = $('.child', '#mainnav ul ul');
    var dropDown = $(dropDownParent).find('ul:first');

    $(dropDown).css({
        top: '27px',
        opacity: 0
    });
    $(dropDownParent).mouseenter(function() {
        $(this).find('ul').eq(0).stop().css({ display: 'block' }).animate({
            top: '32px',
            opacity: 1
        }, 150);
    }).mouseleave(function() {
        $(this).find('ul').eq(0).stop().animate({
            top: '27px',
            opacity: 0
        }, 100, function() {
            $(this).css({ display: 'none' })
        });
    });
}


TABLES.Init = function() {
	/**
	/* Find tables in main content and "re-build" them to match design
	/*
	*/
	if (SYS.pageId == 'subpage') {
		var topTable = $('.topheading', '#main');
		var leftTable = $('.leftheading', '#main');

		if ($(topTable).length > 0) {
			$(topTable).each(function(i) {
				$(this).find('tr').eq(0).children().each(function(i, elm) {
					var th = $('<th>' + $(this).html() + '</th>');
					$(this).replaceWith(th);
					var attributes = $(this)[0].attributes;
					if (attributes) {
						$(attributes).each(function(j, attr) {
							$(th).attr(attr.name, attr.value);
						});
					}
				});
			});
		}
		if ($(leftTable).length > 0) {
			$(leftTable).find('tr').each(function(i, elm) {
				var th = $('<th>' + $(this).children(':eq(0)').html() + '</th>')
				$(this).children(':eq(0)').replaceWith(th);
				var attributes = $(this)[0].attributes;
				if (attributes) {
					$(attributes).each(function(j, attr) {
						$(th).attr(attr.name, attr.value);
					});
				}
			});
		}
	}

	/* FINANCIAL TABLES */
	return;
	var financialTable = $('table.financial-table');
	financialTable.each(function() {
		$(this).wrap($('<div class="financial-table-wrapper"></div>'));
		$(this).find('tr.parent span').prepend($('<a href="javascript:;" class="trigger"><img src="/ui/gfx/ico-table-plus.png" alt=""/></a>')).bind('click', function() {
			$(this).parents('tr').nextUntil('tr.sum').toggle();
			var imgSrc = $(this).find('img').attr('src');
			if (imgSrc.indexOf('-plus') != -1) {
				$(this).find('img').attr('src', '/ui/gfx/ico-table-minus.png');
			} else {
				$(this).find('img').attr('src', '/ui/gfx/ico-table-plus.png');
			};
		})
		$(this).find('tr.sublvl').hide();
	});

};

FUNCTIONS.NewWin = {
	init: function(att, val) {
		if (document.getElementById && document.createElement && document.appendChild) {
			var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
			var strVal = ((typeof val == 'undefined') || (val == null)) ? 'new-win' : val;
			var arrLinks = document.getElementsByTagName('a');
			var oLink;
			var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
			for (var i = 0; i < arrLinks.length; i++) {
				oLink = arrLinks[i];
				if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
					oLink.onclick = FUNCTIONS.NewWin.openWin;
				}
			}
		}
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
			var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	}
};

FUNCTIONS.Push = function() {
	// Conf
	var navParentId = 'pushnav';
	var push = $('#push');
	var pos = $(push).attr('class').indexOf('push-');

	var id = $(push).attr('class').substring(pos + 5, ($(push).attr('class').length - pos + pos));

	var lang = 'sv';
	var url = window.location.href;

	if (url.indexOf('/en/') > -1) lang = 'en';

	$.ajax({
		type: "POST",
		url: "/Templates/Services/TopPushService.asmx/GetTopPushObjects",
		//url: "/jsontest.txt?test=",

		data: "{'pageId':'" + id + "','lang':'" + lang + "'}",
		contentType: 'application/json; charset=utf-8',
		dataType: 'json',
		beforeSend: function() {
			if (!$('#push').hasClass('modal')) {
				$('#' + navParentId).children(':eq(0)').append('<div class="loading"></div>');
			} else if ($('#push').hasClass('modal')) {
				$('#' + navParentId + ' ul').eq(0).hide();
			}
		},
		error: function(e) {
		
		},
		success: function(data) {
			SYS.pushResult = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
			if (!$('#push').hasClass('modal')) {
				if (SYS.pushResult.length > 1) {
				
					// Append images
					for (i = SYS.pushResult.length - 1; i >= 1; --i) {
						$('#push img').eq(0).after('<img src="' + SYS.pushResult[i].image + '" alt="' + SYS.pushResult[i].heading + '" title="' + SYS.pushResult[i].heading + '" />');
					}

					// Create image navigation
					if ($('#thumb').length > 0) $('#thumb').remove();

					// Get images
					var images = $('#push img'); // big images
					$('#' + navParentId + '').append('<ul id="thumb"></ul>');
					$(images.clone()).each(function(i, elm) {
						$('#thumb').append($(elm).attr('width', '54').attr('height', '28'));
						$(elm).wrap('<li></li>');
					});
					$('#thumb li').eq(0).css({ marginLeft: '0' });
					$('#thumb').append('<li id="thumb-selected" />');
					$('#push img').not($('#' + navParentId + ' img')).css({  // only big images
						position: 'absolute',
						top: '7px',
						left: '5px'
					});
					var thumbs = $('#thumb li').not('#thumb-selected'); // image thumbs
					var pushHeight = $(images).eq(0).height();
					
					$('#push').css({ height: pushHeight });
					
					var pushLnkElm = $('#push .push-lnk');
					pushLnkElm.css({ height: pushHeight });
				
					var pushLnkCssHide = { 'cursor':'default' }
					var pushLnkCssShow = { 'cursor':'hand','cursor':'pointer' }
					
					var pushLnk = SYS.pushResult[i].link;
					if (pushLnk) {
						pushLnkElm.attr('href',SYS.pushResult[i].link);
						pushLnkElm.css(pushLnkCssShow);
					} else {
						pushLnkElm.attr('href','#');
						pushLnkElm.css(pushLnkCssHide);
					}
					
					
					// Image click event
					$(images).not(':eq(0)').css({ display: 'none' });
					var animation = false;
					$(thumbs).bind('click', function() {
						if (!animation) {
							animation = true;
							var clickedElm = $(this);
							
							// Reset image auto slide and start from current slide
							FUNCTIONS.PushAutoSlide(SYS.pushIdle, thumbs);
							SYS.pushRunningCount = $(clickedElm).prevAll().length;

							// Swap image
							$(images).fadeOut(1000);
							$(images).eq($(clickedElm).prevAll().length).fadeIn(1000);

							// animate thumb marker
							var position = $(this).position();
							var markerLeft = position.left - 3;
							if ($(clickedElm).prevAll().length == 0) markerLeft = position.left - 10;
							$('#thumb-selected').animate({
								left: markerLeft + 'px'
							}, 'fast');

							// Get new project information
							var currHeight = $('#pushnav div').height();
							$('#pushnav div').css({
								height: 'auto'
							});
															
							var once = false;
							$('#pushnav div').animate({
								opacity: 1
							}, 500, function() {
								if (!once) {
									once = true;
									
									$('#pushnav div').children().remove();									
									$('#pushnav div').append($('<h2>' + SYS.pushResult[clickedElm.prevAll().length].heading + '</h2>'));
									$('#pushnav div').append($(SYS.pushResult[clickedElm.prevAll().length].description));
									
									pushLnk = SYS.pushResult[clickedElm.prevAll().length].link;
									
									if (pushLnk) {
										pushLnkElm.attr('href',pushLnk);
										pushLnkElm.css(pushLnkCssShow);
									} else {
										pushLnkElm.attr('href','#');
										pushLnkElm.css(pushLnkCssHide);
									}
										
									var newHeight = $('#pushnav div').height();
									$('#pushnav div').height(currHeight);
									$('#pushnav div').animate({	height: newHeight }, 500, function() {
										$('#pushnav div').css({ display: 'block' });
										$('#pushnav div').animate({ opacity: 1 }, 200, function() {
											animation = false;
										});
									});
								}
							});

						}
					});
					// Image auto slide
					FUNCTIONS.PushAutoSlide(SYS.pushIdle, thumbs);

					// Image auto slide user interaction
					$('#' + navParentId).mouseenter(function() {
						if (SYS.pushTimeout > 0) clearTimeout(SYS.pushTimeout);
					}).mouseleave(function() {
						FUNCTIONS.PushAutoSlide(SYS.pushIdle, thumbs);
					});

				}
			} else {
				// Create image navigation
				var allImagesLink = $('#thumb li:last-child');
				$('#thumb').remove();
				$('#' + navParentId + '').append('<ul id="thumb"></ul>');
				$('#thumb').hide();
				$(SYS.pushResult).each(function(i, obj) {
					$('#thumb').append('<li><a href="#" name="modal" rel="images" title="' + obj.heading + '"><img src="' + obj.image + '" alt="' + obj.heading + '" title="' + obj.heading + '"  height="28" width="33" /></a></li>');
				});
				$('#thumb').append(allImagesLink);
				$('#thumb li').eq(0).css({ marginLeft: '0' });
				$('#push').css({ height: $(images).eq(0).height() });
			}
		},
		complete: function() {
			// Remove loding, slide up image navigation
			$('#' + navParentId + ' .loading').remove();
			$('#' + navParentId + ' ul').eq(0).slideDown();
			$('#' + navParentId).children(':eq(0)').children().css({ 'opacity': 1 });
		}
	});
};
FUNCTIONS.PushIndex = function() {
    var height = $('#index', '#static').height();
    $('#index', '#static').css({ height: 0 });
    $('#index', '#static').animate({ height: height }, 1500, function() {
        $(this).css({ height: 'auto' });
    });
};
FUNCTIONS.PushAutoSlide = function(time, elms) {
    if (SYS.pushTimeout > 0) clearTimeout(SYS.pushTimeout);
    SYS.pushTimeout = setTimeout(function() {
        SYS.pushRunningCount++;
        if (SYS.pushRunningCount > $(elms).children().length - 1) {
            SYS.pushRunningCount = 0;
        }
        $(elms).eq(SYS.pushRunningCount).trigger('click');
        FUNCTIONS.PushAutoSlide(SYS.pushRunning, elms);
    }, time);
};
FUNCTIONS.AjaxSearch = function() {
	var searchFields = $('.ajax', '#index');
	if (!searchFields[0]) searchFields = $('.ajax', '#content');
	
	$(searchFields).each(function(i, input) {
		$(input).css({
			border: 'none',
			margin: 0,
			padding: 0,
			width: '332px'
		});
		$(input).removeClass('input').wrap('<div class="input" />');
		$(input).parent().css({ position: 'relative' });
		$(input).keyup(function(e) {
			if ($(this).attr('value').length > 3 && e.keyCode >= 65 && e.keyCode <= 90 || $(this).attr('value').length > 3 && e.keyCode >= 48 && e.keyCode <= 57 ||  e.keyCode == 8 || e.keyCode == 46) {
				if ($('#intel-search-result').length == 0) $('body').append('<ul id="intel-search-result"><li class="loading">Loading...</li></ul>');
				var resultList = $('#intel-search-result');
				var pos = $('div.input').offset();
				var posTop = $('div.input').offset().top;
				$(resultList).css({ width: $(input).width() + 6 + 'px' });
				$(resultList).css(pos);
				$(resultList).css('top',posTop+28);
				$.ajax({
					type: "POST",
					url: "/templates/services/SearchService.asmx/AddressSearch",
					cache: false,
					data: "{'searchString':'" + $(this).attr('value') + "' }",
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					beforeSend: function() {

					},
					error: function() {
					},
					success: function(data) {
						var result = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
						$('#intel-search-result li').remove();
						var item = '';
						$(result).each(function(i, obj) {
							item += '<li>' + obj.display + '</li>'
						});
						$(resultList).append(item);
						$(resultList).find('li').bind('click', function() {
							$(searchFields).val($(this).text());
							$(resultList).hide();
						});
					},
					complete: function() {

					}
				});
			}
		});
	});
};
FUNCTIONS.PremiseListSearchMap = function() {
    var map = $('#area-search-map ul');
    $(map).css({
		background:'transparent url(/ui/gfx/bg-search-list-map.png) no-repeat 0 0'
    });
    $(map).find('li').css({
        border: '1px solid #83807d',
        background: 'none',
        position:'absolute'
    });
    // Visa alla
    $(map).children(':eq(0)').css({
        display: 'none'
    });
    $(map).children(':eq(1)').css({
        width: 78 + 'px',
        height: 48 + 'px',
        top: 63 + 'px',
        left: 65 + 'px'
    });
    $(map).children(':eq(2)').css({
        width: 57 + 'px',
        height: 30 + 'px',
        top: 29 + 'px',
        left: 45 + 'px'
    });

    $(map).children(':eq(3)').css({
        width: 47 + 'px',
        height: 19 + 'px',
        top: 116 + 'px',
        left: 130 + 'px'
    });
    $(map).children(':eq(4)').css({
        width: 190 + 'px',
        height: 13 + 'px',
        top: 0,
        left: 20 + 'px',
        borderTop: 'none'
    });
    $(map).children(':eq(5)').css({
        width: 190 + 'px',
        height: 13 + 'px',
        bottom: 0,
        left: 20 + 'px',
        borderBottom: 'none'
    });
    $(map).find('li').each(function(i, elm) {
        $(elm).attr('title', $(elm).text());
        $(elm).find('span').css({
            display: 'block',
            width: $(this).width() + 'px',
            height: $(this).height() + 'px',
            background: '#000000',
			opacity: 0.11
        });
    });
    $(map).find('input').css({
		position:'absolute',
		left:'-9999em'
    });
    $(map).find('label').css({
		position:'absolute',
		left:'-9999em'
    });
    $(map).find('span').mouseover(function() {
		$(this).css({
			background:'#7b308d'
		});
    }).mouseout(function() {
		$(this).css({
			background:'#000000'
		});
	});
	$('#extended-search').after('<div id="area-filter" />');
	var fieldset = $('#extended-search fieldset');
    $(map).find('li').bind('click', function() {
		var input = $(this).find('input');
        $(this).toggleClass('selected');
        if($(this).hasClass('selected')){
			$(input).attr('checked', true);
        } else{
			$(input).attr('checked', false);
        }
        SYS.premiseDistrict = '';
        var selectedSubDistrict = '';
		$(map).find('input').each(function(i, inp){
			if($(inp).is(':checked')){
				SYS.premiseDistrict += $(inp).val() + ',';
				selectedSubDistrict += $(inp).parent().text();
			}
		});
		if ($(fieldset).is(':visible'))FUNCTIONS.PremiseFilterUpdate();
		FUNCTIONS.PremiseSearchUpdate();
        //$(selectedArea).text(selectedSubDistrict);
    });
    var searchTab = $('#content-tab-nav');
    var searchResult = $('#search-result');
    $(searchTab).find('li').bind('click', function(){
	    if (!$(this).hasClass('selected')) {
	        $(this).parent().children().toggleClass('selected');
	        $(searchResult).children('div').hide();
	        $(searchResult).children('div').eq($(this).prevAll().length).show();
	        FUNCTIONS.PremiseSearchUpdate();
	        FUNCTIONS.PremiseFilterUpdate();
	    }
	    //return false;
    });
    
    //sort result list
    $('#search-result-list table tr th span').bind('click', function(){
        $(this).parent().parent().find('th').removeClass('selected');
        $(this).parent().addClass('selected');
        var sortBy = $(this).attr('class').substring($(this).attr('class').lastIndexOf('-')+1,6);
        SYS.premiseSearchSortBy = sortBy;
        FUNCTIONS.PremiseSearchUpdate();
    });
};
FUNCTIONS.PremiseSearch = function(){
    // disable form submit on page
    $('form').submit(function(){return false});
    
	var extendedSearch = $('#extended-search');
	var fieldset = $(extendedSearch).find('fieldset').eq(0).css({
		display:'none'
	});
	var extendText = $(extendedSearch).find('h2');
	$(extendText).hide();
	$(extendedSearch).prepend('<span id="extend">' + $(extendText).text() + '</span>');
	$('#extend').bind('click', function(){
		$(this).toggleClass('selected');
		$(this).hasClass('selected') == false ? $(fieldset).fadeOut(function(){
		    SYS.premiseSearchString = '';
		    SYS.premiseType = '';
		    SYS.premiseDistrict = ''		 
		    $('#area-search-map').find('input').each(function(i, inp){
			    if($(inp).is(':checked')){
				    SYS.premiseDistrict += $(inp).val() + ',';
			    }
		    });
		    FUNCTIONS.PremiseSearchUpdate();
		}) : $(fieldset).fadeIn(function(){
		        FUNCTIONS.PremiseFilterUpdate();
		    });
	});	
	FUNCTIONS.PremiseSearchUpdate();
	FUNCTIONS.PremiseExtendedFilterUpdate();
};
FUNCTIONS.PremiseSearchUpdate = function() {

	// search filter to URI
	//console.log(FUNCTIONS.getUrlVars());


	var searchResultList = $('#search-result-list');
	var searchResultMap = $('#search-result-map');
	var searchResultTableContent = $(searchResultList).find('table');

	var searchResultDisplayType = ($('#content-tab-nav').find('li.selected').attr('id'));
	switch (searchResultDisplayType) {
		case 'search-list':
			var searchMethod = 'PremisesSearch';

			break;
		case 'search-map':
			var searchMethod = 'PremisesMapSearch';

			break;
	}
	
	var searResultInfo = $('#area-filter');
	$.ajax({
		type: "POST",
		//type: "GET",
		url: "/Templates/Services/SearchService.asmx/" + searchMethod,
		//url: "/ui/js/ajax-search-premise.js",
		//url: "/ui/js/ajax-search-premise-map.js",
		cache: false,
		data: "{'district':'" + SYS.premiseDistrict + "', 'minArea':" + SYS.premiseMin + ", 'maxArea':" + SYS.premiseMax + ", 'searchString':'" + SYS.premiseSearchString + "', 'type':'" + SYS.premiseType + "', 'sortBy':" + SYS.premiseSearchSortBy + ", 'ascending':" + SYS.premiseSearchAscending + ", 'language':''}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		beforeSend: function() {
			$('#search-result h2, #content-tab-nav').fadeIn('slow');
			switch (searchResultDisplayType) {
				case 'search-list':
					if ($(searchResultList).is(':hidden')) {
						$(searchResultList).fadeIn('slow');
					}
					$(searchResultTableContent).find('tbody').remove();
					break;
				case 'search-map':

					break;
			}
			$(searResultInfo).html('<img src="/ui/gfx/loader-violette.gif" alt="" />&nbsp;Searching for vacant premises...');
		},
		error: function(e) {
			$(searResultInfo).html('<span class="error">Something went wrong. Please try to search again.</span>');
		},
		success: function(data) {
			var result = (typeof data.d) == 'string' ? eval('(' + data.d + ')') : data.d;
			
			var length = 0;
			if (searchResultDisplayType === 'search-map'){
			    $(result).each(function(i, obj){
			        length += obj.Premises.length
			    });
			}else{
			    length = result.length
			}

			if (length == 1){
			    $(searResultInfo).html('<span>Found ' + length + ' object</span>&nbsp;&nbsp;&nbsp;<a href="#search-result" title="Show result">Show result</a>');
			}else{
			    $(searResultInfo).html('<span>Found ' + length + ' objects</span>&nbsp;&nbsp;&nbsp;<a href="#search-result" title="Show result">Show result</a>');
			}
			switch (searchResultDisplayType) {
				case 'search-list':
					var searchMethod = 'PremisesSearch';
					$('#searching', searchResultList).remove();
					var thumbs = []
					var tbody = '<tbody>';
					if (result.length > 0) {
						$(result).each(function(i, obj) {
							thumbs[i] = '<img src="' + obj.Image + '" alt="" />';
													
							if (i == 0) {
								tbody += '<tr class="first">';
							} else {
								tbody += '<tr>';
							}
							tbody += '<td>' + obj.District + '</td>';
							tbody += '<td>';
							tbody += '<a name="tooltip" href="' + obj.Link + '" title="' + obj.Street + '"  rel="' + obj.Image + '" class="new-win">' + obj.Street + '</a><br />' + obj.Description;
							tbody += '</td>';
							tbody += '<td>' + obj.Area + ' sqm</td>';
							tbody += '<td>' + obj.Type + '</td>';
							tbody += '</tr>';
						});
					} else {
						$(searResultInfo).html('<span class="error">This search returned no result.</span>');
					}
					tbody += '</tbody>';
					$(searchResultTableContent).append(tbody);
					
					$(tbody).find('a').each(function(i, elm){
					    $(elm).data('tooltipImage', thumbs[i]);
					});
					
					//console.log($(tbody).find('a').data());

					break;
				case 'search-map':
				
					var initMapSettings = {
						zoom: 13,
						center: new google.maps.LatLng(59.339493, 18.056717),
						mapTypeId: google.maps.MapTypeId.ROADMAP
					};

					var map = new google.maps.Map(document.getElementById('gmap-canvas'), initMapSettings);
					          
					var location = [];
					var premises = [];
					var pinUrl = [];
					$(result).each(function(i, obj) {
						location[i] = [obj.Location.Address, obj.Location.Latitude, obj.Location.Longitude, i];
						premises[i] = obj.Premises;
						pinUrl[i] = '/ui/gfx/gmap-pin-'+obj.Premises.length+'.png';
						if (obj.Premises.length > 10) pinUrl[i] = '/ui/gfx/gmap-pin-10.png';
					});
				
					var shadow = new google.maps.MarkerImage('/ui/gfx/gmap-pin-shadow.png',
                                    new google.maps.Size(28, 7),
                                    new google.maps.Point(0, 0),
                                    new google.maps.Point(0, 7));
					var shape = {
						coord: [1, 1, 1, 20, 18, 20, 18, 1],
						type: 'poly'
					};
					
					var infowindow = new google.maps.InfoWindow();
					var bounds = new google.maps.LatLngBounds();
					
					var contentStringArray = [];
					
					$(location).each(function(i, obj) {
					    var image = new google.maps.MarkerImage(pinUrl[i],
                            new google.maps.Size(18, 27),
                            new google.maps.Point(0, 0),
                            new google.maps.Point(0, 27));
						var premiseLatLng = new google.maps.LatLng(obj[1], obj[2]);
						var marker = new google.maps.Marker({
							position: premiseLatLng,
							map: map,
							shadow: shadow,
							icon: image,
							shape: shape,
							title: obj[0],
							zIndex: obj[3]
						});
						var contentString = '';
						$(premises[i]).each(function(j, info) {
							contentString += '<div class="gmap-premises">' +
							'<img src="' + info.Image + '" alt="' + info.Street + '" width="100" />' +
                            '<p><strong><a href="' + info.Link + '" title="' + info.Street + '" class="new-win">' + info.Street + '</a></strong><br />' +
                            info.District + '<br />' +
                            info.Type + ', ' + info.Area + ' sqm<br />' +
                             info.Description + '</p>' +
                            '</div>';
						});
					    contentStringArray[i] =  contentString;
						infowindow.maxWidth = 340;
						google.maps.event.addListener(marker, 'click', function() {
							infowindow.content = contentStringArray[i];
							infowindow.open(map, marker);
						});
						
						bounds.extend(premiseLatLng);
					    map.fitBounds(bounds);
					});
					break;
			}
		},
		complete: function() {
			FUNCTIONS.NewWin.init();
		}
	});
};
FUNCTIONS.PremiseFilterUpdate = function() {
	var areaCont = $('#area-search-map ul li');
	var area = {};
	$(areaCont).each(function(i, elm){
	    if ($(elm).find('input')) {
            area[$(elm).find('label').text()] = $(elm).find('input').val();
        }
	});
    var dropDown = $('#extended-search').find('ul').eq(0);
    var newDropdown = '';
    newDropdown += '<select name="' + $(dropDown).attr('id')  + '" class="func-FUNCTIONS.PremiseExtendedFilterUpdateArea">';
    for (key in area){
        newDropdown += '<option value="">' + key + '</option>';
        $(area[key].split(',')).each(function(i, obj){
            newDropdown += '<option value="' + obj + '">' + obj + '</option>';
        });
    }
    newDropdown += '</select>';
    $(dropDown).next().remove();
    $(dropDown).replaceWith(newDropdown);
    $('#content').FormSelectRestyled(true, 'form-drop-down', '--', 0);    
};
FUNCTIONS.PremiseExtendedFilterUpdate = function(){
    var extendedSearch = $('#extended-search');
    var textInput = $('.input', extendedSearch);
    $(textInput).keyup(function(e) {
		if ($(this).attr('value').length > 3 && e.keyCode >= 65 && e.keyCode <= 90 || $(this).attr('value').length > 3 && e.keyCode >= 48 && e.keyCode <= 57 ||  e.keyCode == 8 || e.keyCode == 46) {
			SYS.premiseSearchString = $(this).val();
			FUNCTIONS.PremiseSearchUpdate();
		}
	});
};
FUNCTIONS.PremiseExtendedFilterUpdateArea = function(id){
    var value = $('#extended-search input[name=' + id + ']').val();
    SYS.premiseDistrict = value;
    FUNCTIONS.PremiseSearchUpdate();
};
FUNCTIONS.PremiseExtendedFilterUpdateType = function(id){
    var value = $('#extended-search input[name=' + id + ']').val();
    SYS.premiseType = value;
    FUNCTIONS.PremiseSearchUpdate();
};
FUNCTIONS.AreaSlider = function(areaSlider) {
	$(areaSlider).each(function(i, elm) {
		if ($(elm).parent().hasClass('search')) {
			$(elm).find('fieldset').before('<ul class="premise-size clearfix"><li class="small"><a href="#" title="Small premise">Small premise</a></li><li class="medium"><a href="#" title="Medium premise">Medium premise</a></li><li class="large"><a href="#" title="Big premise">Big premise</a></li></ul>').remove();
			$(elm).find('ul.premise-size').after('<div id="slider-' + i + '" class="slider"><div></div></div><input type="text" id="size-' + i + '" name="size-' + i + '" class="size" />');

			var sizeFilterMin = $(elm).parent().find('input[name=size-filter-min]').val();
			var sizeFilterMax = $(elm).parent().find('input[name=size-filter-max]').val();
			var SliderStarValues = [];
            
			if (sizeFilterMin >= 0) {
				SliderStarValues[0] = sizeFilterMin;
				SYS.premiseMin = FUNCTIONS.getValFromPos(sizeFilterMin);
			} else {
				SliderStarValues[0] = SYS.sliderMinKvm;
				SYS.premiseMin = SYS.sliderMinKvm;
			}
			if (sizeFilterMax >= 0) {
				SliderStarValues[1] = sizeFilterMax;
				SYS.premiseMax = FUNCTIONS.getValFromPos(sizeFilterMax);
			} else {
				SliderStarValues[1] =  SYS.sliderMaxKvm / 3;
				SYS.premiseMax = FUNCTIONS.getValFromPos(SYS.sliderMaxKvm / 3);
			}
			FUNCTIONS.PremiseListSearchMap();
			FUNCTIONS.PremiseSearch();

			$('#slider-' + i + ' div').slider({
				range: true,
				values: [SliderStarValues[0], SliderStarValues[1]],
				min: SYS.sliderMinKvm,
				max: SYS.sliderMaxKvm,
				step: SYS.sliderStep,
				slide: function(event, ui) {
					$('#size-' + i).val(thousands(FUNCTIONS.getValFromPos(ui.values[0])) + ' - ' + thousands(FUNCTIONS.getValFromPos(ui.values[1])) + ' sqm');
				},
				stop: function(event, ui) {
					SYS.premiseMin = FUNCTIONS.getValFromPos(ui.values[0]);
					SYS.premiseMax = FUNCTIONS.getValFromPos(ui.values[1]);
					FUNCTIONS.PremiseSearchUpdate();
					//console.log('Min: ' + SYS.premiseMin + ', ' + 'Max: ' + SYS.premiseMax);
				}
			});
		} else if ($(elm).hasClass('col')) {
			$(elm).find('fieldset').before('<ul class="premise-size clearfix"><li class="small"><a href="#" title="Small premise">Small premise</a></li><li class="medium"><a href="#" title="Medium premise">Medium premise</a></li><li class="large"><a href="#" title="Big premise">Big premise</a></li></ul>').remove();
			var submitName = $(elm).find('input[type=submit]').attr('name');
			$(elm).find('ul.premise-size').after('<div id="slider-' + i + '" class="slider"><div></div></div><input type="text" id="size-' + i + '" name="' + submitName + '-size" class="size" /><input type="hidden" id="min-' + i + '" name="' + submitName + '-min" value="" /><input type="hidden" id="max-' + i + '" name="' + submitName + '-max" value="" />');

			$('#slider-' + i + ' div').slider({
				range: true,
				values: [SYS.sliderMinKvm, SYS.sliderMaxKvm / 3],
				min: SYS.sliderMinKvm,
				max: SYS.sliderMaxKvm,
				step: SYS.sliderStep,
				slide: function(event, ui) {
					$('#size-' + i).val(FUNCTIONS.getValFromPos(ui.values[0]) + ' - ' + FUNCTIONS.getValFromPos(ui.values[1]) + ' sqm');
					$('#min-' + i).val(ui.values[0]);
					$('#max-' + i).val(ui.values[1]);
				}
			});
		}
		$('#slider-' + i, $(elm)).append('<span class="left">' + SYS.sliderMinKvm + ' sqm</span><span class="right">' + thousands(SYS.sliderMaxKvm) + ' sqm</span>');
		$('#size-' + i).val(FUNCTIONS.getValFromPos($('#slider-' + i + ' div').slider('values', 0)) + ' - ' + FUNCTIONS.getValFromPos($('#slider-' + i + ' div').slider('values', 1)) + ' sqm');
		$('#min-' + i).val($('#slider-' + i + ' div').slider('values', 0));
		$('#max-' + i).val(Math.round($('#slider-' + i + ' div').slider('values', 1)));
        //console.log('Min: ' + SYS.premiseMin + ', ' + 'Max: ' + SYS.premiseMax);
       
        
		var premiseSize = $('ul.premise-size a');
		var minMaxValues = [];
		$(premiseSize).bind('click', function() {
			var className = $(this).parent().attr('class');
			if (className == 'small') {
				$('#slider-' + i + ' div').slider('option', 'values', [SYS.sliderMinKvm, SYS.sliderMaxKvm / 3]).slider('enable');
				$('#size-' + i).val(thousands(SYS.sliderMinKvm) + ' - ' + thousands(SYS.sliderInterval1) + ' sqm');
				minMaxValues = $('#slider-' + i + ' div').slider( "option", "values" );
				$('#min-' + i).val(minMaxValues[0]);
				$('#max-' + i).val(Math.round(minMaxValues[1]));
				SYS.premiseMin = SYS.sliderMinKvm;
				SYS.premiseMax = SYS.sliderInterval1;
			} else if (className == 'medium') {
				$('#slider-' + i + ' div').slider('option', 'values', [SYS.sliderMaxKvm / 3, SYS.sliderMaxKvm / 3 * 2]).slider('enable');
				$('#size-' + i).val(thousands(SYS.sliderInterval1) + ' - ' + thousands(SYS.sliderInterval2) + ' sqm');
				minMaxValues = $('#slider-' + i + ' div').slider( "option", "values" );
				$('#min-' + i).val(Math.round(minMaxValues[0]));
				$('#max-' + i).val(parseInt(minMaxValues[1]));
				SYS.premiseMin = SYS.sliderInterval1;
				SYS.premiseMax = SYS.sliderInterval2;
			} else if (className == 'large') {
				$('#slider-' + i + ' div').slider('option', 'values', [SYS.sliderMaxKvm / 3 * 2, SYS.sliderMaxKvm]).slider('enable');
				$('#size-' + i).val(thousands(SYS.sliderInterval2) + ' - ' + thousands(SYS.sliderMaxKvm) + '+ sqm');
				minMaxValues = $('#slider-' + i + ' div').slider( "option", "values" );
				$('#min-' + i).val(parseInt(minMaxValues[0]));
				$('#max-' + i).val(Math.round(minMaxValues[1]));
				SYS.premiseMin = SYS.sliderInterval2;
				SYS.premiseMax = SYS.sliderMaxKvm;
			}
			FUNCTIONS.PremiseSearchUpdate();
			return false;
		});
	});
};
FUNCTIONS.getUrlVars = function() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
	for (var i = 0, m = hashes.length, hash = null; i < m; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
};
FUNCTIONS.getValFromPos = function(pos) {
    var o = 0;
    var p = 0;
    var v;
    for (var i = 0, m = SYS.intervals.length, obj1 = null; i < m; i++) {
        obj1 = SYS.intervals[i];
        if (pos > o + obj1.len) {
            o += obj1.len;
            p += obj1.max;
        } else {
            if (obj1.log && p > 0) {
                v = Math.exp(Math.log(p) + (pos - o) * (Math.log(obj1.max) - Math.log(p)) / obj1.len);
            } else {
                v = p + (pos - o) * (obj1.max - p) / obj1.len;
            }
            for (var j = 0, n = SYS.intervals.length, obj2 = null; j < n; j++) {
                obj2 = SYS.rounding[j];
                v = Math.round(v / obj2.r) * obj2.r;
                if (v <= obj2.v) break;
            }
            return v;
        }
    }
    return -1;
};
FUNCTIONS.Modal = function(content, pos) {
    $('body').append('<div id="fade"></div>');
    var fade = ('#fade');
    $(fade).css({
        width: SYS.winWidth,
        height: SYS.docHeight,
        opacity: 0
    });
    $(fade).fadeTo('normal', 0.8, function() {
        if (content == 'sitemap') {
            $.ajax({
                type: "GET",
                url: "/[MOCKUPS]/sitemap-ajax.html",
                cache: false,
                data: "{ }",
                contentType: "application/html; charset=utf-8",
                dataType: "html",
                beforeSend: function() {
                    $('body').append('<div id="modal" class="sitemap shadow"><span id="close"><span>Close X</span></span><div id="modal-inner" class="clearfix"></div>');
                    $('#modal').css({
                        height: '0px',
                        left: SYS.winWidth / 2 - $('#modal').width() / 2
                    });
                    $('#modal-inner').append('<div id="loading">Loading ' + content + '</div>');
                },
                error: function() {
                    $('#modal-inner').append('<div id="error">There was an error loading the ' + content + '.<br />It seems that it got lost on its way to your screen. Please try again.</div>');
                    $('#modal-inner div').css({ opacity: 0 });
                },
                success: function(result) {
                    $('#modal-inner').append(result);
                    $('#modal-inner div').css({ opacity: 0 });
                },
                complete: function() {
                    $('#loading').remove();
                    $('#modal').animate({
                        height: $('#modal-inner').height()
                    }, function() {
                        $('#modal-inner div').animate({ opacity: 1 }, 'fast');
                    });
                }
            });
        } else if (content == 'images' || content == 'allimages') {
            $('body').append('<div id="modal" class="images shadow"><span id="close"><span>Close X</span></span><div id="modal-inner" class="clearfix"></div>');
            FUNCTIONS.ModalUpdate();
            $(SYS.pushResult).each(function(i, elm) {
                $('#modal-inner').append('<div><h1>' + elm.heading + '</h1><img src="' + elm.image + '" alt="' + elm.heading + '" title="' + elm.heading + '" /></div>');
            });
            if (content == 'allimages') {
                var width = $('#modal-inner').width();
                var height = $('#modal-inner').height();
                $('#modal-inner').find('div').css({ display: 'none' });

                $('#modal').animate({
                    width: width + 40,
                    height: height,
                    marginLeft: -width / 2 - 20
                }, function() {
                    $('#modal-inner').find('div').fadeIn('fast', function() {
                        FUNCTIONS.ModalUpdate();

                    });
                });
            }
            if (content == 'images') {
                var currImg = $('#modal-inner').find('div').eq(pos);
                $('#modal').after('<ul id="modal-image-nav"><li class="arrow prev"><span>Previous</span></li><li class="count">' + ($(currImg).prevAll().length + 1) + '/' + SYS.pushResult.length + '</li><li class="arrow next"><span>next</span></li></ul>');
                $('#modal-image-nav').css({
                    left: SYS.winWidth / 2 - $('#modal-image-nav').width() / 2,
                    display: 'none'
                });
                if (pos == 0) {
                    $('#modal-image-nav li.prev').addClass('inactive');
                } else if (pos == SYS.pushResult.length - 1) {
                    $('#modal-image-nav li.next').addClass('inactive');
                }
                Cufon.replace('#modal h1');
                var widthArray = [];
                $('#modal-inner').find('img').each(function(i, elm) {
                    widthArray[i] = $(elm).width();
                });
                
                $('#modal-inner').find('div').css({ display: 'none' });
                $('#modal').animate({
                    width: $(currImg).width() + 40 + 'px',
                    height: $(currImg).height(),
                    marginLeft: -$(currImg).width() / 2 - 20 + 'px'
                }, function() {
                    $(currImg).fadeIn();
                    $('#modal-image-nav').fadeIn();
                    $('#modal-image-nav li.arrow').bind('click', function() {
                        if ($(this).hasClass('inactive')) return;
                        $('#modal-image-nav li.arrow').removeClass('inactive');
                        if ($(this).hasClass('next')) {
                            var img = $(currImg).next();
                            if ($(img).nextAll().length == 0) {
                                $(this).addClass('inactive');
                            }
                        } else if ($(this).hasClass('prev')) {
                            var img = $(currImg).prev();
                            if ($(img).prevAll().length == 0) {
                                $(this).addClass('inactive');
                            }
                        }
                        $(currImg).fadeOut('fast', function() {
                            $('#modal').animate({
                                width: widthArray[$(img).prevAll().length] + 40 + 'px',
                                height: $(img).height(),
                                marginLeft: -widthArray[$(img).prevAll().length] / 2 - 20 + 'px'
                            }, 'normal', function() {
                                $(img).fadeIn('fast');
                                $('.count', '#modal-image-nav').text($(img).prevAll().length + 1 + '/' + SYS.pushResult.length);
                                currImg = img;
                            });

                        });
                    });
                });
            }
        }
    });
    $(fade + ', #close').live('click', function() {
        $(fade).nextAll().remove();
        $(fade).remove();
    });
};
FUNCTIONS.ModalUpdate = function() {
    $('#fade').css({
        width: SYS.winWidth,
        height: SYS.docHeight
    });
    $('#modal').css({
        left: SYS.winWidth / 2 - $('#modal-sitemap').width() / 2
    });
    if ($('#modal-image-nav').length > 0) {
        $('#modal-image-nav').css({
            left: SYS.winWidth / 2 - $('#modal-image-nav').width() / 2
        });
    }
};
FUNCTIONS.ToolTip = function(){
    $('a[name="tooltip"]').live('mouseover', function(){
        var tooltip = $('<div id="tooltip"><p></p></div>');
        var offset = $(this).offset();
        $('body').append(tooltip);
        var img = new Image();
        $(img).load(function () {
            $(tooltip).find('p').empty().append(this);
            $(tooltip).css({
                top:offset.top - $(tooltip).outerHeight() + 'px',
                left:offset.left + 'px'
            }).stop().fadeIn(200);
        }).attr('src', $(this).attr('rel'));
    }).live('mouseout', function(){
         $('#tooltip').remove();
    });
};
FUNCTIONS.ToggleBox = function(box){
    $(box).children().not(':first-child').hide();
    $(box).children(':first-child').bind('click', function(){
        $(box).children().toggle();
        return false;
    });
};
FUNCTIONS.ImageCaption = function(){
    $('img.caption').each(function(i, elm){
        $(elm).load(function() {
            $(elm).css({display:'block'});
            $(elm).wrap('<div class="image-caption" />').parent().css({
                width:$(elm).width() + 'px'
            }).append('<span>' + $(elm).attr('alt') + '</span>');
        }).attr('src', $(elm).attr('src'));
    });
};
FUNCTIONS.Share = function(){
    var share = $('.email', '#share');
    $(share).bind('click', function(){
        if($('#share-box').length == 0){
            var shareBox = $('<div id="share-box"><div><p><strong>Share page by e-mail</strong><label for="toEmail">Receiver (e-mail)</label><br /><input id="toEmail" name="toEmail" type="text" class="input" /><label for="fromEmail">Sender (e-mail)</label><br /><input id="fromEmail" name="fromEmail" type="text" class="input" /><span class="btn btn-gray"><input id="share-submit" type="submit" value="Send"></span></p></div><span id="share-close"></span></div>');
            var offset = $(this).offset();
            $('body').append(shareBox);
            $(shareBox).TextfieldPlaceholders();
            $(shareBox).css({
                top:offset.top + $(this).height() + 'px',
                left:offset.left - 20 + 'px'
            }).stop().fadeIn(300, function(){
                $('#share-close').bind('click', function(){
                    $(shareBox).remove();
                });
                $('#share-submit').bind('click', function(){
                    var input =  $('input[name]', shareBox);
                    var reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;  
                    $(input).each(function(i, inp){     
                        var matched = $(inp).val().match(reg); 
                        if(matched == null){
                           $(inp).addClass('error');
                        }else{
                            $(inp).removeClass('error');
                        }
                    });
                    if($('.error', shareBox).length == 0){
                        var to =  $('input[name="toEmail"]', shareBox).val();
                        var from =  $('input[name="fromEmail"]', shareBox).val();
                        var url = window.location.href;
                        $.ajax({
                            type: "POST",
                            url: "/Templates/Services/MailService.asmx/SendMail",
                            data: "{'to':'" + to + "','from':'" + from + "','url':'" + url + "'}",
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            beforeSend: function() {
        		               $('p', shareBox).addClass('loading');
                            },
                            error: function(e) {
        			            $('p', shareBox).animate({
        		                    opacity:0
        		                }, 'fast', function(){
        		                    $(shareBox).append('<span id="share-sent">Message not sent.<br />Try again.</span>');
        		                });
                            },
                            success: function(data) {
                                $('p', shareBox).removeClass('loading').animate({
        		                    opacity:0
        		                }, 'fast', function(){
                                    if (data.d == true){
        		                        $(shareBox).append('<span id="share-sent">Message sent!</span>');
                                    }else if(data.d == false){
                                        $(shareBox).append('<span id="share-sent">Message not sent.<br />Try again.</span>');
                                    }
                                    var t = setTimeout('$("#share-box").remove()',3000);
                                });
                            }
                        });
                    }
		        });
            });
        }
        return false;
    });
};
FUNCTIONS.FontReplace = function() {
    Cufon.replace('h1');
};

/*PLUGINS*/

/* Form Select Restyled v1.2.1 Beta - jQuery Plugin
* Copyright (c) 2010 Patrik Totero
* Author: 	Patrik Totero, www.patriktotero.com
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
	$.fn.FormSelectRestyled = function($nameAsId, $className, $noSelectSign, $maxHeight) {
		return this.each(function() {
			var $parent = $(this);
			$parent.find('select').each(function(i, elm) {
				var $selectWidth = $(elm).width();
				$(elm).find('option').each(function(i, elm) {
					if ($(elm).attr('value') == '') {
						$(elm).text($noSelectSign + $(elm).text() + $noSelectSign);
					}
					if (i == 0) {
						$(elm).wrapInner('<span />');
						$($parent).data('form-values', { selectValue: $(elm).text() });
					}
					var $innerHtml = $(elm).html();
					if ($(elm).val() == '') {
						$(elm).replaceWith('<li class="' + $className + '-section">' + $innerHtml + '</li>');
					} else {
						$(elm).replaceWith('<li>' + $innerHtml + '</li>');
					}
				});
				var $innerHtml = $(elm).html();
				var $ul = $('<ul />').css({ width: $selectWidth });
				var classFunctions = $(elm).attr('class').split(' ');
				$(elm).replaceWith($ul);
				if ($nameAsId) {
					var $id = $(elm).attr('name');
					$ul.attr('id', $id);
					var $input = $('<input type="hidden" name="' + $id + '" value="' + $($parent).data('form-values').selectValue + '" />');
					$ul.after($input);
				}
				$ul.html($innerHtml);
				$ul.attr('class', $className);
				var $li = $ul.find('li');
				$($li[0]).clone().appendTo($li[0]);
				$li.each(function(i, elm) {
					if (i > 0) {
						$(elm).detach().appendTo($li[0]);
					}
				});
				$ul.find('li li').wrapAll('<ul class="' + $className + '-drop" />');
				$('.' + $className + '-drop', $ul).css({
					top: $li.innerHeight(),
					width: $ul.width()
				});
				$ul.append('<li class="' + $className + '-open"><span /></li>');
				$('.' + $className + '-open span', $ul).css({
					width: $selectWidth + 'px',
					height: $ul.height() + 'px'
				}).bind('click', function() {
					var offset = $ul.offset();
					var $clone = $(this).parent().prev().find('ul').clone();
					$('body').append($clone);
					$clone.wrap('<div id="' + $className + '-clone" />').removeClass();
					$clone.find('li').not('.' + $className + '-section').bind('click', function() {
						$($li[0]).find('span').eq(0).text($(this).text());
						if ($nameAsId) $($input).attr('value', $(this).text());
					});
					if($maxHeight > 0){
					    $clone.parent().css({
					        height:$maxHeight + 'px',
					        'overflow':'hidden',
					        'overflow-y':'scroll'
					    });
					}
					$clone.parent().css({
						display: 'none',
						position: 'absolute',
						top: offset.top + $ul.height() + 'px',
						left: offset.left + 'px',
						width: $ul.width()
					}).fadeIn('fast', function() {
						$(this).one('mouseleave', function() {
							$(this).fadeOut('fast', function() {
								$(this).remove();
							});
						}).one('click', function() {
							$(classFunctions).each(function(i, obj) {
								if (obj.indexOf('func-') != -1) {
									var func = obj.substring(5, obj.length);
                                    /*
                                     * TO-DO: make check if function exists before calling it
                                    */
									/*if (typeof func === 'function') {
										eval(func + '();');
									}*/
									eval(func + '("' + $ul.attr("id") + '");');
								}
							});
							$(this).fadeOut('fast', function() {
								$(this).remove();
							});
						});
					});
				});
			});
		});
	}
})(jQuery);

/* Textfield Placeholders - jQuery Plugin
* Copyright (c) 2009 Palle Zingmark
* Author: 	Palle Zingmark, www.palleman.nu
*         	Philip Hofstetter, www.gnegg.ch
* Released with the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
(function($) {
    $.fn.TextfieldPlaceholders = function() {
        return this.each(function() {
            var $parent = $(this);
            $parent.find('input:text[value=""],input:password[value=""], textarea').each(function(i) {
                var $input = $(this);
                var $placeholder = $($input).attr('placeholder');
                var $basecolors = ['#000000', 'rgb(0, 0, 0)'];
                var $color = $($input).css('color');
                var $hascolor = jQuery.inArray($color, $basecolors);
                if (typeof $placeholder == 'undefined' || $placeholder == '') {
                    $placeholder = $parent.find('label[for="' + $($input).attr('id') + '"]').text();
                }
                if (typeof $placeholder == 'string' || $placeholder != '') {//## OR ABORT
                    if ($input.attr('type') == 'password') {
                        var $proxy = $('<input type="text" />');
                        var $original_input = $input;
                        $proxy.attr('class', $input.attr('class'));
                        $proxy.attr('style', $input.attr('style'));
                        $proxy.insertAfter($input);
                        $input.hide();
                        $input = $proxy;
                    }
                    $input.attr('value', $placeholder);
                    $input.attr('title', $placeholder);
                    if ($hascolor || $hascolor != -1) {
                        $input.css('color', '#aeaeae');
                    }
                    $input.bind('focus', function() {
                        if ($input.attr('value') == $placeholder) {
                            if ($original_input) {
                                $input.hide();
                                $original_input.show();
                                $input = $original_input;
                                $input.focus();
                            }
                            $input.attr('value', '');
                            $input.css('color', $color);
                        }
                    });
                    ($original_input || $input).bind('blur', function() {
                        if ($input.attr('value') == $placeholder || $input.attr('value') == '') {
                            if ($original_input) {
                                $original_input.hide();
                                $proxy.show();
                                $input = $proxy;
                            }
                            $input.attr('value', $placeholder);
                            if ($hascolor || $hascolor != -1) {
                                $input.css('color', '#aeaeae');
                            }
                        }
                    });
                }
            });
        });
    };
})(jQuery);


function thousands(nStr) {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ' ' + '$2');
    }
    return x1 + x2;
}
