﻿/*global jQuery*/
(function (window) {
	"use strict";
	var $ = window.jQuery,
		view;

	view = {

		init: function () {
			//model.addToQue(false, ['GetStuff', { email: 'stuff' }], view.doStuff);

			this.page.observeLinks();
			this.util.isCompleted = true;
		},

		/* Handles Google analytics tracking. */
		analytics: {

			trackVideo: function (site, id, event, worth) {
				var action, // string
				    category, // string
				    label; // string
				
				
				category = 'Video';
				action = event;
				label = site;

				window._gaq.push(['_trackEvent', category, action, label, parseInt(worth, 10)]);
			},

			init: function () {
				/* Track anchor clicks. */
				var action, // string
					category, // string
					label, // string
					worth; // number

				$('a').click(function () {
					var that = this, // object
					    t = $(that), // object
					    href = that.href, // string
					    domain = document.domain, // string
					    pathDomain = href.match(/^(http\:\/{2})?(w{3}\.)?([\w\-]+)(\.[\w]+)(\/($)?|$)/), // string
					    isInternalRe = new RegExp("^http:\\/{2}" + domain), // boolean
					    isInternal = (isInternalRe).test(href), // boolean
					    docRe = /[\w]+$/i, // string
					    hdnGaWorthFile = document.getElementById('hdnGAWorthFile'), // object
					    hdnGaWorthMail = document.getElementById("hdnGAWorthMail"), // object
					    hdnGaWorthExternal = document.getElementById("hdnGAWorthExternal"); // object

					if (t.hasClass('file')) { /* File-download links */
						category = 'File-' + href.match(docRe)[0];
						action = 'Download';
						label = decodeURIComponent(href).match(/([\w\s\+\-\u007E\u00c0-\u00ff]+)(\.\w+)$/gi).join().replace(/(\.\w+)$/i, ""); //fileName (without suffix);
						worth = hdnGaWorthFile ? hdnGaWorthFile.value : 0;
					} else if ((/^mailto\:/).test(href)) { /* Mailto-links */
						category = 'Contact';
						action = 'Mail';
						label = href.replace(/^mailto\:/gi, ""); //address;
						worth = hdnGaWorthMail ? hdnGaWorthMail.value : 0;
					} else if (!isInternal) { /* External links */
						category = 'External';
						action = 'Clicked';
						label = pathDomain ? pathDomain[0] : 0;
						worth = hdnGaWorthExternal ? hdnGaWorthExternal.value : 0;
					}

					if (action && category) {
						window._gaq.push(['_trackEvent', category, action, label, parseInt(worth, 10)]);
					}
				});
			}
		},

		// YouTube JavaScript Player API
		youtube: {

			embed: function (movieId, width, height, parent) {
				var timespan = new Date().getTime(),
				    videoId = 'ytplayer' + timespan,
				    params = { allowfullscreen: 'true', allowScriptAccess: 'always', wmode: 'opaque' },
					atts = { id: videoId },
					version = 3;

				parent.after('<div id="' + videoId + '" class="ytplayer"/>');
				swfobject.embedSWF('http://www.youtube.com/e/' + movieId + '?version=' + version + '&enablejsapi=1&autohide=1&playerapiid=' + videoId + '&autohide=1&fs=1&feature=player_embedded&cc_load_policy=0&controls=1&showinfo=0&iv_load_policy=3&modestbranding=1&rel=0&fmt=18',
                       videoId, width, parseInt(height, 10), "8", null, null, params, atts);
			},
			events: {
				onStateChange: function (newState, playerId) {
					var videoId = $('#' + playerId).closest('.youTubeMovie').find('.hdnYoutubeId').val();
					
					if (newState === 0) {
						$.view.analytics.trackVideo('Youtube', videoId, 'ended', document.getElementById('hdnGAWorthVideoEnd').value);
					}
					if (newState === 2) {
						$.view.analytics.trackVideo('Youtube', videoId, 'paused', document.getElementById('hdnGAWorthVideoPause').value);
					}
					if (newState === 1) {
						document.getElementById(playerId).setPlaybackQuality('hd720');
						$('#' + playerId).closest('.youTubeMovie').find('.youTubeLogo').hide();
						$.view.analytics.trackVideo('Youtube', videoId, 'started', document.getElementById('hdnGAWorthVideoStart').value);
					}
				}
			},
			controls: {
				init: function () {
					window.onYouTubePlayerReady = function (playerId) {
						window[playerId + 'onStateChangeCallback'] = (function (pId) {
							return function (newState) {
								view.youtube.events.onStateChange(newState, pId);
							};
						} (playerId));
						var el = document.getElementById(playerId);
						el.addEventListener("onStateChange", playerId + 'onStateChangeCallback');
					};
				}
			},
			modules: function (module) {
				var videoWidth = module.width();
				if (module.find('.hdnYoutubeId').length && module.find('.videoOverlay').length) {
					window.isStarted = false;
					view.youtube.embed(module.find('.hdnYoutubeId').val(), videoWidth, module.find('.hdnMovieHeight').val(), module.find('.videoOverlay'));
				}
			},

			// Fallback for iPhone, iPad and iPod
			mobileFallback: {
				init: function () {
					var ua = window.navigator.userAgent;

					if ($(".fallbackContainer").length && $(".videoContainer").length) {
						if ((/(iPad|iPod|iPhone)/ig).test(ua)) {
							$('.mobileFallback').each(function () {
								$(this).find('iframe').attr('width', $(this).closest('.youTubeMovie').width()).attr('frameborder', 0);
							});
							this.showFallback();
						} else if (!window.swfobject.hasFlashPlayerVersion("8") && (/(msie)/ig).test(ua)) {
							this.showNoFlash();
						}
					}
				},
				showFallback: function () {
					$(".fallbackContainer").show();
					$(".videoContainer").hide();
				},
				showNoFlash: function () {
					$(".noflashContainer").show();
					$(".videoContainer").hide();
				}
			},


			init: function () {
				$('.youTubeMovie').each(function () {
					view.youtube.modules($(this));
				});
			}
		},


		page: {
			init: function () {
				$('a.newWindow').click(function (e) {
					e.preventDefault();
					window.open($(this).attr('href'));
				});

				$('#intranetNewsList .showAll a').click(function () {
					$('#intranetNewsList li').removeClass('hidden');
					$('#intranetNewsList .showAll').addClass('hidden');
				});
			},

			load: function () {
				if ($('.js_bridge .active_image').length) {
					var elem = $('.image' + $('.js_bridge .active_image').val()).parent();
					if ($('.js_bridge .active_image').val() !== '0') {
						$('html,body').animate({ scrollTop: elem.offset().top + 40 }, 1000);
					}
				}
			},

			searchBox: null,
			searchUrl: $('#sUrl').val(),
			defaultSearchValue: '',
			activeSuggestion: null,

			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');
			},

			observeLinks: function () {
				$('a').click(function () {
					if ($(this).attr('rel') == 'external') {
						window.open($(this).attr('href'));
						$(this).blur();
						return false;
					}
					return true;
				});
			},

			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 () {
				document.location.href = $.view.page.searchUrl + '?find=' + $(this).html() + $.view.search.getAdvancedQuery();
			},

			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) {
					this.searchingTerm = $('#googleResults').html();
					window.loadMap();

					$('li.maplink > a.close').click(function () {
						$('#googleMap').slideUp();
						$(this).hide();
						$('#googleMapStreetBtn').hide();
					});
				};

				$('#googlePOIs a').click(function (e) {
					e.preventDefault();
					$(this).blur();

					$('#googleResults').html(view.map.searchingTerm);

					var searchtermKey = $(this).attr('rel') || 'livsmedel';

					$.view.map.getNearBy(searchtermKey);
					$('#googlePOIs a').removeClass('active');
					$(this).addClass('active');
				});

			},

			getNearBy: function (searchTerm) {
				if (typeof (map) == 'undefined') {
					setTimeout('this.getNearBy(searchTerm)', 1000);
				}

				currentZoom = map.getZoom();
				currentLatLng = map.getCenter();

				map.setZoom(17);
				map.setCenter(origLatLng);
				map_localsearch.doSearch(searchTerm);


				var l = localSearch.results;

			},

			toggleStreetView: function () {
				//var fenwayPark = new GLatLng(42.345573,-71.098326);
				if ($('#googleMapStreet:visible').length || $('#googleMapStreetNoMap:visible').length) {
					map.setCenter(currentLatLng);
					$('#googleMapStreet').hide();
					$('#googleMapStreetNoMap').hide();
					$('#googleMap').show();
					$('#googleMapStreetBtn').removeClass('active').find('a').html('Street View');
				} else {
					map.setCenter(window.origLatLng);
					$('#googleMapStreet').show();
					$('#googleMap').hide();
					$('#googleMapStreetBtn').addClass('active').find('a').html('Karta');
					this.streetView = new window.GStreetviewPanorama(document.getElementById("googleMapStreet"), { latlng: map.getCenter() });
					window.GEvent.addListener(this.streetView, "error", function () {
						$('#googleMapStreet').hide();
						$('#googleMapStreetNoMap').show();
						return;
					});
				}
			}
		},

		officeList: {
			init: function () {
				var i,
					l = window.pageData.officeList.length,
					office,
					nColumn = 0,
					nColumns = Math.ceil(window.pageData.officeList.length / 4);

				for (i = 0; i < l; i += 1) {
					office = window.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 : '')) + (office.expanded == 1 ? ' expanded' : ''))
					}).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');
					}

					/* Uppsala ska inte vara expanderad vid document.ready() */
					/* else if (office.childCount > 0 && office.expanded == 0){
					$('#office' + i + ' a').click(function (e) {
					e.preventDefault();
					$(this).parent().nextUntil('li:not(.l1)').toggleClass('hidden');
					}).addClass('expandable');
					}*/

				}

				$('#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 () {
						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 () {
							$(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 () {
				if ($('#searchWrapper').length) {
					$('#searchResultsWrapper #tabs a').click(function (e) {
						e.preventDefault();
						document.location.href = $(this).attr('href').split('#')[0] + '&cords=' + $.view.util.getScrollXY() + $.view.search.getAdvancedQuery();
					});

					$('#searchAdvanced, #searchSubmit').mouseover(function () {
						$.view.util.getCursor(this);
					});

					$('#searchAdvanced').click(function () {
						$('#advancedWrapper').toggleClass('hidden');
						$('#searchSuggestions').addClass('hidden');
					});

					$('.ui-state-hover').mouseover(function () {
						$.view.util.getCursor(this);
					});
					$('.ui-slider-handle').mousedown(function () {
						$(this).blur();
					});


					this.setUpSlider('#advancedWrapper #sliderPris', 10000);
					this.setUpSlider('#advancedWrapper #sliderRum', 1);
					this.setUpSlider('#advancedWrapper #sliderTomtAreal', 100);
					this.setUpSlider('#advancedWrapper #sliderBoArea', 10);
					this.setUpSlider('#advancedWrapper #sliderAvgift', 100);

					$('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').removeClass('hidden');
												$('#searchSuggestions').mouseover(function () {
													$.view.util.getCursor(this);
												});

												$('#searchSuggestions li').click($.view.page.populateSearch);

											}
											else {
												$('#searchSuggestions').addClass('hidden');
											}
										}
									});
								}
								else {
									$('#searchSuggestions').addClass('hidden');
								}
							}
						})
						.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').hasClass('hidden')) {
									sUrl += '?' + $.param({ find: val }) + $.view.search.getAdvancedQuery();
									if (val.length > 0) {
										if (hemnet) {
											window.open(sUrl);
										}
										else {
											document.location.href = sUrl;
										}
									}
									return false;
								}
								else {
									sUrl += '?' + $.param({ find: $('#li' + this.activeSuggestion).html() }) + $.view.search.getAdvancedQuery();
									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');
								}
							}
							return true;
						});
				}
			},

			setUpSlider: function (selector, step) {
				$(selector + ' .slider').slider({
					range: true,
					min: parseInt($(selector + ' input.fromInit').val(), 10),
					max: parseInt($(selector + ' input.toInit').val(), 10),
					values: [parseInt($(selector + ' input.from').val(), 10),
							parseInt($(selector + ' input.to').val(), 10)],
					step: step,
					slide: function (event, ui) {
						$.view.search.handleSlide(event, ui, selector, $(this).slider('option', 'max'));
					}
				});

				/* Known bug, if page are reloaded wrong values are parsed */
				$.view.search.handleSlideHeaders($(selector + ' .slider').slider('values'), selector, $(selector + ' input.toInit').val());
			},

			handleSlide: function (event, ui, selector, max) {
				$(event.originalTarget).blur();

				$.view.search.handleSlideHeaders(ui.values, selector, max);

				$(selector + ' label span.from').html($.spaceNumber(ui.values[0], 3, ' '));
				$(selector + ' label span.to').html($.spaceNumber(ui.values[1], 3, ' '));

				$(selector + ' input.from').val(ui.values[0]);
				$(selector + ' input.to').val(ui.values[1]);

				$('#advancedWrapper .isAdvanced').val('1');
			},

			handleSlideHeaders: function (values, selector, max) {
				if (parseInt(values[0], 10) === parseInt(values[1], 10)) {
					$(selector + ' label span.fromHead').addClass('hidden');
					$(selector + ' label span.toHead').addClass('hidden');
					$(selector + ' label span.from').addClass('hidden');
					$(selector + ' label span.above').addClass('hidden');

					if (parseInt(max, 10) === parseInt(values[1], 10)) {
						$(selector + ' label span.aboveCap').removeClass('hidden');
					} else {
						$(selector + ' label span.aboveCap').addClass('hidden');
					}
				} else {
					$(selector + ' label span.fromHead').removeClass('hidden');
					$(selector + ' label span.toHead').removeClass('hidden');
					$(selector + ' label span.from').removeClass('hidden');
					$(selector + ' label span.aboveCap').addClass('hidden');

					if (parseInt(max, 10) === parseInt(values[1], 10)) {
						$(selector + ' label span.above').removeClass('hidden');
					} else {
						$(selector + ' label span.above').addClass('hidden');
					}
				}
			},

			getAdvancedQuery: function () {
				var r = '';
				if ($('#advancedWrapper .isAdvanced').val() == "1") {
					$('#advancedWrapper input').each(function () {
						var arr = $(this).attr('id').split('_');
						if (arr[arr.length - 1].indexOf('Init') === -1) {
							if ($('#' + $(this).attr('id') + 'Init').length) {
								if ($(this).val() !== $('#' + $(this).attr('id') + 'Init').val()) {
									r += '&' + arr[arr.length - 1] + '=' + $(this).val();
								}
							}
							else {
								r += '&' + arr[arr.length - 1] + '=' + $(this).val();
							}
						}
					});
				}
				return r;
			}
		},

		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);
	});
	$(window).load(function () {
		$.runLoad($.view);
	});

} (window));

//deprecated 
c9 = {};
c9.era = {};
c9.era.page = {};
c9.era.page.clickOfficeTab = function () {};
c9.era.page.hoverOfficeTab = function () {};
c9.era.page.observeSearch = function () {};

c9.util = {};
