﻿/*global jQuery*/
"use strict";
(function () {
	var window = this,
		$ = jQuery,
		model,
		view;
	
	view = {
		init : function () {
			//model.addToQue(false, ['GetStuff', { email: 'stuff' }], view.doStuff);
			
			this.util.isCompleted = true;
		},
		
		page : {
			searchBox : null,
			searchUrl : $('#sUrl').val(),
			defaultSearchValue : '',	
			activeSuggestion : null,
			
			checkToSubmitLogin : function(e) {
				var charCode = e.charCode || e.keyCode || e.which;
				if (charCode === 13) {
					e.preventDefault();
					
					__doPostBack('ctl00$FrameWorkRegion$MainBodyRegion$ctl00','');
				}
			},
			
			showAllElementsByClassName : function (selector) {
				$(selector).css({ display: 'block' });
			},
			
			hideAllElementsByClassName : function (selector) {
				$(selector).hide();
			},
			
			toggleBids : function (sender) {
				sender.blur();
				if ($('.BidHistory')) {
					$('.BidHistory').each(function(index, item) {
						$(item).toggle();
					});
				}
				
				$(sender).toggleClass('active');
			},
			
			
			
			observeInput : function(dDom, e, sValue, sAction){
				switch(e.type)
				{
					case 'blur':
						if(dDom.value == '')
						{
							dDom.style.color = '#8b8b8b';
							dDom.value = sValue;   
						}
						break;  
					case 'focus':
						if(dDom.value == sValue)
						{
							dDom.value = ''; 
							dDom.style.color = '#000';
						}
						break;  
					case 'keypress':
						if(e.keyCode == Event.KEY_RETURN && typeof(sAction) != undefined){
							eval(sAction);
							
							try {
								if ($.view.util.isIE)
									e.returnValue = false; // The IE way
								else
									e.preventDefault(); // The DOM way
							}	
							catch (err){}
								
						}
						break;  
				}
			},
			
			populateSearch : function(dDom) {
				document.location.href = $.view.page.searchUrl + '?find=' + $(this).html();
			},
			
			checkOfficeTabTimer : function() {
				this.timer = 0;
			},
			
			clickOfficeTab : function(sClosed, sOpened) {
				var groudZero = (view.util.isIE6 ? "-20px" : "0px"), 
					top = ($('#officesContainer').get(0).style.top.length == 0 ? 0 : $('#officesContainer').get(0).style.top),
					tabWidth = 162;
	    		
				$('#officesDataFramerTop').get(0).style.height = '2px';
	    		
				if (this.timer == 0) {
					if (top != groudZero) {
						/* open */
	    				this.timer = setTimeout('$.view.page.checkOfficeTabTimer()',400);
	    			
						$('#officesContainer').css('top', '-' + $('officesDataFramer').getHeight() + 'px');
						$('#officesWrapper').css({
							width: '764px',
							height: $('officesDataFramer').getHeight() + $('officesTab').getHeight() + 100 + 'px'
						});
					    
						$('#officesContainer').animate({
							left : '-4px',
							top : groudZero
						}, 300, function(){
							$('#officesTabLink').html(sOpened);
						});
					 
					}
					else {
						/* close */
	    				$('#officesDataFramerTop').css('height', '0px');
						this.timer = setTimeout('$.view.page.checkOfficeTabTimer()',400);
	    				
	    				$('#officesContainer').animate({
							left : parseInt(tabWidth - $('#officesContainer').width() - 12) + 'px',
							top : '-' +  parseInt(parseInt($('#officesDataFramer').height()) - parseInt(groudZero.replace('px',''))) + 'px'
						}, 300, function(){
							$('#officesTabLink').html(sOpened);
							$('#officesWrapper').css({
								height : $('officesTab').getHeight() + 'px',
								width : tabWidth + 'px'
							}, 300);
						});
					}
				}
			},
			
			clickPersonInfo : function(sName, sender) {
				$(sender).blur();
				var divHeight = ($('#' + sName).get(0).style.height == '') ? '0px' : $('#' +sName).get(0).style.height;
				
				if(divHeight != (parseInt($('#' + sName + 'contents').get(0).offsetHeight) + 'px')) {
					$('#' + sName).css('visibility', 'visible');
					$('#' + sName).animate({
						height : parseInt($('#' + sName + 'contents').get(0).offsetHeight) + 'px',
						paddingBottom : parseInt(15) + 'px'
					}, 200);
				}
				else {
					$('#' + sName).animate({
						height : '0px',
						paddingBottom : '0px'
					}, 200, function () {
						$('#' + sName).css('visibility', 'hidden');
					});
				}
			}
		},
		
		
		map : {
			init : function () {
				if ($('#googleMap').length) {
					try { 
						loadMap(); 
					} catch(ex) {}
				};
				
				$('#googlePOIs a').click(function (e) {
					e.preventDefault();
					$(this).blur();
					$.view.map.getNearBy($(this).html()); 
					$('#googlePOIs a').removeClass('active'); 
					$(this).addClass('active');
				});
				
			},
			
			getNearBy : function(searchTerm){
				if (typeof(map) != 'undefined') {
					map.setCenter(new GLatLng(latOrig , lngOrig), 17);
				}
				else
					setTimeout('this.getNearBy(searchTerm)',1000);

				localSearch.execute(searchTerm);
				var l = localSearch.results;
				
				//map.setZoom(12)
					
			},
			
			toggleStreetView : function () {
				//var fenwayPark = new GLatLng(42.345573,-71.098326);
				if ($('#googleMapStreet:visible').length || $('#googleMapStreetNoMap:visible').length) {
					$('#googleMapStreet').hide();
					$('#googleMapStreetNoMap').hide();
					$('#googleMap').show();
					$('#googleMapStreetBtn').removeClass('active').find('a').html('Street View');
				} else {
					$('#googleMapStreet').show()
					$('#googleMap').hide();
					$('#googleMapStreetBtn').addClass('active').find('a').html('Karta');
					this.streetView = new GStreetviewPanorama(document.getElementById("googleMapStreet"), { latlng: map.getCenter() });
					GEvent.addListener(this.streetView, "error", function (errorCode) {
						$('#googleMapStreet').hide();
						$('#googleMapStreetNoMap').show();
						return;
					});
				}
			}
		},
		
		officeList : {
			init : function () {
				var i,
					l = pageData.officeList.length,
					office,
					list,
					nColumn = 0,
					nColumns = Math.ceil(pageData.officeList.length / 4);	
			
				for (i = 0; i < l; i += 1) {
					office = pageData.officeList[i];
					
					if (i === 0 || (i % nColumns) === 0) {
						nColumn += 1;
						$('<ul/>', {
							id: 'findOffice' + nColumn
						}).appendTo('#officesData');
					}
					
					$('<li />', {
						id: 'office' + i,
						className: (office.level > 1 ? 'hidden l' + office.level : (office.level > 0 ? 'l' + office.level : ''))
					}).append($('<a/>', {
						href: (office.childCount > 0 ? 'javascript:void(0);' : office.url),
						text: office.name
					})).appendTo('#findOffice' + nColumn);
					
					if (office.childCount > 0 && office.level > 0) {
						$('#office' + i + ' a').click(function (e) {
							e.preventDefault();
							$(this).parent().nextUntil('.l1').toggleClass('hidden');
						}).addClass('expandable');
					}
				/** TODO: HEMNET **/	
				}
				
				$('#officesTab a#officesTabLink').hover(function () {
					$(this).parent().css({ marginTop : '-2px' });
				}, function () {
					$(this).parent().css({ marginTop : '0px' });
				}).click(function (e) {
					e.preventDefault();
					var top, topC, left, heightPx, width, 
						zero = !!(typeof document.body.style.maxHeight == 'undefined' && !$.support.opacity) ? -20 : 0;
					
					if ($(this).hasClass('isOpen')) {
						left = parseInt(150 - $('#officesContainer').width()) + 'px';
					    topC = '-' +  (parseInt($('#officesDataFramer').height(), 10) + 4 - zero) + 'px';
						heightPx = $('#officesTab').height() + 'px';
						width = '162px';
						$(this).removeClass('isOpen').html($(this).attr('rel').split('|')[0]);
					} else {
						heightPx = $('#officesDataFramer').height() + $('#officesTab').height() + 100 + 'px';
						top = '-' + $('#officesDataFramer').height() + 'px';
					    left = '-4px';
					    topC = zero + 'px';
						width = '764px';
						$(this).addClass('isOpen').html($(this).attr('rel').split('|')[1]);
						$('#officesWrapper').css({ height: heightPx, width : width});
						$('#officesContainer').css({ top: top});
					}
					
					$('#officesContainer').animate({
						left: left,
						top: topC
				    }, function () {
						$('#officesWrapper').css({ height: heightPx, width : width});
					});
				});
			}
		},
		
		object: {
			similarScrollDisabled : false,
			similarItemWidth : 0,
			similarScrollWidth : 0,
			oldLeft : 0,
			init: function(){
				
				var tempItemWidth = 0,
					tempScrollWidth = 0;
				
				$('#divSilimarScroll div.contents').each(
					function(i) {
						if(tempItemWidth == 0) {
							tempItemWidth = parseInt($(this).width(), 10) + parseInt($(this).css('padding-right'), 10);
						}
						tempScrollWidth += $(this).width() + parseInt($(this).css('padding-right'), 10);
					}
				)
				this.similarItemWidth = tempItemWidth;
				this.similarScrollWidth = tempScrollWidth;
				
				$('#divSilimarScroll').width(tempScrollWidth + 'px');
				
				if (parseInt(this.similarItemWidth) >= parseInt(this.similarScrollWidth)) {
				   $('#divSimilar div.divSimilarLinks').each (
						function(i) {
							$(this).css('display', 'none');
						}
					)
				}
				
				$('#divSimilar div.divSimilarLinks #aSilimarPrev').click(function() {
					$(this).blur();
					$.view.object.scrollSimilar('left');
				});
				$('#divSimilar div.divSimilarLinks #aSilimarNext').click(function() {
					$(this).blur();
					$.view.object.scrollSimilar('right');
				});
			},
			
			scrollSimilar : function(direction) {	
				if ($('#divSilimarScroll').css('left') == '') {
					$('#divSilimarScroll').css('left','0px');
				}
				$.view.object.oldLeft = parseInt($('#divSilimarScroll').css('left'), 10);
				
				if (!$.view.object.similarScrollDisabled) {
					$.view.object.similarScrollDisabled = true;
					switch (direction)
					{
						case "right":
							$('#divSilimarScroll').animate({
								left: (parseInt($.view.object.oldLeft, 10) - parseInt($.view.object.similarItemWidth, 10))
							}, 500, function() {
								if (parseInt($('#divSilimarScroll').css('left'), 10) <= parseInt($.view.object.similarItemWidth, 10) - parseInt($.view.object.similarScrollWidth, 10)) {
									$('#aSilimarNext').css('visibility', 'hidden');
								}
								else {
									$('#aSilimarNext').css('visibility', 'visible');
								}
								
								$.view.object.similarScrollDisabled = false;
								$('#aSilimarPrev').css('visibility', 'visible');
							});
							break;
							
						case "left":
							$('#divSilimarScroll').animate({
								left: parseInt($.view.object.oldLeft, 10) + parseInt($.view.object.similarItemWidth, 10)
							}, 500, function() {
								if (parseInt($('#divSilimarScroll').css('left')) == 0) {
									$('#aSilimarPrev').css('visibility','hidden');
								}
								else {
									$('#aSilimarPrev').css('visibility','visible');
								}
								
								$.view.object.similarScrollDisabled = false;
								$('#aSilimarNext').css('visibility','visible');
							});
							break;
							
					}
				}
			}
		},
		
		widgets : {
			init : function () {
				$('.widgets .wrapper a.open').click(function(e) {
					e.preventDefault();
					$('.widgets .wrapper .form').css('display','none');
					$(this).siblings('.form').css('display','block');
					$('.widgets .wrapper .form .result').css('display','none');
					$('.widgets .wrapper .form .box').css('display','block');
				});
				$('.widgets .wrapper a.close').click(function(e) {
					e.preventDefault();
					$('.widgets .wrapper .form').css('display','none');
				});

				$('.widgets .wrapper #divShare .box a.icon').click(function(e) {
					e.preventDefault();
					window.open($(this).attr('href'));
					$('.widgets .wrapper .form').css('display','none');
				});
				
			}
		},
		
		search : {
			activeSuggestion : null,
			init : function () {
			
				$('#advancedWrapper #sliderTomtAreal').slider({
					range: true,
					min: 0,
					max: 500,
					values: [0, 10000],
					slide: function(event, ui) {
						//$("#amount").val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}});
				$('#advancedWrapper #sliderRum').slider({
					range: true,
					min: 0,
					max: 500,
					values: [0, 10000],
					slide: function(event, ui) {
						//$("#amount").val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}});
				$('#advancedWrapper #sliderPris').slider({
					range: true,
					min: 0,
					max: 500,
					values: [0, 10000],
					slide: function(event, ui) {
						//$("#amount").val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}});
				$('#advancedWrapper #sliderBoArea').slider({
					range: true,
					min: 0,
					max: 500,
					values: [0, 10000],
					slide: function(event, ui) {
						//$("#amount").val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}});
				$('#advancedWrapper #sliderAvgift').slider({
					range: true,
					min: 0,
					max: 500,
					values: [0, 10000],
					slide: function(event, ui) {
						//$("#amount").val('$' + ui.values[0] + ' - $' + ui.values[1]);
					}});
				
				
				$('.ui-slider-handle').mouseover(function () {
					$.view.util.getCursor(this);
				});
				$('.ui-slider-handle').mousedown(function (e) { 
					$(e.currentTarget).blur();
				});
			
			
				$('input[id$=inptSearch]').data('standardText',	$('input[id$=inptSearch]').val())
				.focus(function () {
					if ($(this).val() === $(this).data('standardText')) {
						$(this).css({ color: '#000000' }).val('');
					}
				})
				.blur(function () {
					$(this).val(function (index, val) {
						return (val === '' ? $(this).css({ color: '#8b8b8b' }).data('standardText') : val);
					});
				})
				.keyup(function(e) {
					var charCode = e.charCode || e.keyCode || e.which,
						val = $(this).val();
					if(charCode !== 13 && charCode !== 38 && charCode !== 40)
					{
						if (val.length > 2)		
						{
							$.ajax({
								url: '/ui/pages/LiveSearchResponse.aspx?find=' + encodeURIComponent(val),
								success : function(transport){
									if (transport.length > 0)
									{
										$('#ulSuggestions').html(transport);
										$('#searchSuggestions').css('display','block');
										
										
										$('#searchSuggestions li').click($.view.page.populateSearch);
									}
									else
									{
										$('#searchSuggestions').css('display','none');
									}
									
									
									
								}
							})
						}
						else
						{
							$('#searchSuggestions').attr('style','display:none');
						}
					}
				})
				.keydown(function(e) {
					var charCode = e.charCode || e.keyCode || e.which,
						val = $(this).val(),
						sUrl = $.view.page.searchUrl,
						hemnet = $(this).hasClass('hemnet');
						
	                if(charCode === 13) {
						e.preventDefault();
						
						if($('#searchSuggestions').css('display') != 'block') {
							sUrl += '?' + $.param({ find: val});
							if (val.length > 0) {
								if (hemnet) {
									window.open(sUrl);
								}
								else {
									document.location.href = sUrl;
								}
							}
							return false;
						}
						else {
							sUrl += '?' + $.param({ find: $('#li' + this.activeSuggestion).html()});
							if (this.activeSuggestion != null) {
								if (hemnet) {
									window.open(sUrl);
								}
								else {
									document.location.href = sUrl;
								}
							}
							return false;
						}
					}
					else if(charCode === 38)
					{
						if (this.activeSuggestion != null) {
							var prev = $('#li' + this.activeSuggestion).prev();
							if (prev.length > 0) {
								$('#li' + this.activeSuggestion).removeClass('active');
								this.activeSuggestion--;
								$('#li' + this.activeSuggestion).addClass('active');
							}
							else { 
								$('#li' + this.activeSuggestion).removeClass('active');
								this.activeSuggestion = null;
							}
						}
					}
					else if(charCode == 40) {
						if (this.activeSuggestion != null)
						{
							var next = $('#li' + this.activeSuggestion).next();
							if (next.length > 0)
							{
								$('#li' + this.activeSuggestion).removeClass('active');
								this.activeSuggestion++;
								$('#li' + this.activeSuggestion).addClass('active');
							}
						}
						else {
							this.activeSuggestion = 1;
							$('#li1').addClass('active');				
						}
					}      
				});
			}
		},
		
		widget : {
			init : function () {
				$('#image_widget .close, .ui-widget-overlay, #viewPhotoWrapper').live('click', function () {
					$('#image_widget').dialog('destroy');
					$('#image_widget').attr('style', 'display:none');
				});
			},
		
			loadImages : function (imageId, imageIndex, source) {
				var w = (source === 'hemnet' ? 640 : ($(document).width() - 100 ) > 1044 ? 1044 : ($(document).width() - 100 ));
				
				$('#image_widget').load('/ui/widgets/ViewPhoto.aspx?GID='+ escape(imageId) + '&imageId='+ escape(imageIndex) + '&width='+ escape((w - 20 )) + '&source='+ escape(source), function () {
					$('#image_widget img:first').load(function () {
						$('#image_widget').dialog({
							closeText : '',
							modal: true,
							width: (source === 'hemnet' ? 660 : w),
							open: function () {
								$('#image_widget').dialog('option', 'height', $('#image_widget img:first').height() + 90);
							}
						});
					});
				});
			},
			
			changeImage : function (imageId, imageIndex, source) {
				var w = (source === 'hemnet' ? 640 : ($(document).width() - 100 ) > 1044 ? 1044 : ($(document).width() - 100 )),
					height;
				
				$('#image_widget').load('/ui/widgets/ViewPhoto.aspx?GID='+ escape(imageId) + '&imageId='+ escape(imageIndex) + '&width='+ escape(w-20) + '&source='+ escape(source), function () {
					$('#image_widget img:first').load(function () {
						
						height = $('#image_widget img').height() + 90;
						$('#image_widget').dialog('option', 'height', height);
						$('#image_widget').css({ height: height + 'px'})
					});
				});
				
			}
		},
		
		util : {
			isIE6 : !!(typeof document.body.style.maxHeight == 'undefined' && !$.support.opacity),
			isCompleted : false,
			
			getCursor : function(dDom) {	
				if (document.all) {
					dDom.style.cursor = 'hand';
				} else {
					dDom.style.cursor = 'pointer';
				}
			},
			
			getScrollXY : function() {
				var scrOfX = 0, scrOfY = 0;
				if( typeof( window.pageYOffset ) == 'number' ) {
					//Netscape compliant
					scrOfY = window.pageYOffset;
					scrOfX = window.pageXOffset;
				} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
					//DOM compliant
					scrOfY = document.body.scrollTop;
					scrOfX = document.body.scrollLeft;
				} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
					//IE6 standards compliant mode
					scrOfY = document.documentElement.scrollTop;
					scrOfX = document.documentElement.scrollLeft;
				}
				return [ scrOfX, scrOfY ];
			},
			
			encode : function (string) {
				return escape(this._utf8_encode(string));
			},

			// public method for url decoding
			decode : function (string) {
				return this._utf8_decode(unescape(string));
			},

			// private method for UTF-8 encoding
			_utf8_encode : function (string) {
				string = string.replace(/\r\n/g,"\n");
				var utftext = "";

				for (var n = 0; n < string.length; n++) {

					var c = string.charCodeAt(n);

					if (c < 128) {
						utftext += String.fromCharCode(c);
					}
					else if((c > 127) && (c < 2048)) {
						utftext += String.fromCharCode((c >> 6) | 192);
						utftext += String.fromCharCode((c & 63) | 128);
					}
					else {
						utftext += String.fromCharCode((c >> 12) | 224);
						utftext += String.fromCharCode(((c >> 6) & 63) | 128);
						utftext += String.fromCharCode((c & 63) | 128);
					}

				}

				return utftext;
			},

			// private method for UTF-8 decoding
			_utf8_decode : function (utftext) {
				var string = "";
				var i = 0;
				var c = c1 = c2 = 0;

				while ( i < utftext.length ) {

					c = utftext.charCodeAt(i);

					if (c < 128) {
						string += String.fromCharCode(c);
						i++;
					}
					else if((c > 191) && (c < 224)) {
						c2 = utftext.charCodeAt(i+1);
						string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
						i += 2;
					}
					else {
						c2 = utftext.charCodeAt(i+1);
						c3 = utftext.charCodeAt(i+2);
						string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
						i += 3;
					}

				}

				return string;
			}
		},
		
		flow : {
			maxItems : 0,
			maxWidth : 0,
			offsetLeft : 37,
			offsetTop : 10,
			hideTimeout : null,
			
			init : function () {
				/*
				$('.dock').css('display', 'block');
				$('.dock').each(function (index, elem) {
					if (index % 2 != 0) {
						var container = $(elem).find('.dock-container'),
							p = $(elem).find('.dock-container p');
						
						view.flow.maxItems = view.flow.maxItems < p.length ? p.length : view.flow.maxItems;
						
						p.each(function (index, elem) {
							p.eq(parseInt('-' + (index + 1), 10)).appendTo(container);
						});
					}
				});
				
				$('.dock').Fisheye(
					{
						container: '.dock-container',
						maxWidth: 40,
						itemWidth:	117,
						items: 'p',
						itemsText: 'span',
						proximity: 90,
						valign: 'center',
						halign : 'center'
					}
				);
				*/
				
				$('.dock-item').mousemove(function(event) {
					if ($(this).children('span:not(.noBubble)').length) {
						clearTimeout(view.flow.hideTimeout);
						$('#bubble').css('display','block');
						
						$('#bubbleText').html($(this).children('span').html());
						$('#bubble').css('left', event.pageX - view.flow.offsetLeft);
						$('#bubble').css('top', event.pageY - $('#bubble').height() - view.flow.offsetTop);
					}
				});
				
				$('#bubble').mousemove(function(event) {
					clearTimeout(view.flow.hideTimeout);
					$(this).css('top', event.pageY - $('#bubble').height() - view.flow.offsetTop);
				});
				
				$('.dock-item').mouseout(function(event) {
					view.flow.hideTimeout = setTimeout(function() {$('#bubble').css('display','none');}, 100);
				});
				
				if ($('.dock-item').length > 0) {
					$('#framework').mouseover(function(event) {
						if ($('#bubble').css('display') !== 'none') {
							$('#bubble').css('display','none');
						}
					});
				}
			} 
		}
	};
	
	$.extend({ view: view });
	
	$(document).ready(function () {
		$.runInit($.view);
	});
	
}());

//deprecated 
c9 = {};
c9.era = {};
c9.era.page = {};
c9.era.page.clickOfficeTab = function () {};
c9.era.page.hoverOfficeTab = function () {};
c9.era.page.observeSearch = function () {};

c9.util = {};