/*
	Requires that the following variables are printed before this script in html script block:
	var ajaxrequest_baseurl - base path for ajax requests
	var housesfolderid - id of folder node containing all house categories
	var realestateimg_width/height - dimensions for real estate imagery in opened state
	var showdebug - show debug messages (true/false)
*/ 


var allcategories_maincontent;

// milliseconds before ajax loader indicator appears
var ajaxload_waittime = 200;
var ajaxloader_timeout;

// milliseconds before sending request after a keypress (enables pressing multiple keys before request)
var keyboard_waittime = 500;
var keyboard_timeout;

var ajaxrequest_baseurl_view = ajaxrequest_baseurl + "/view";
var ajaxrequest_baseurl_search = ajaxrequest_baseurl + "/search";


// MOVE to ez side when search available
var searchinstruction = "Etsi";

// Variable to hold tells whether page is loaded from external link or ajax
var fromExURL = "";

// Define console to prevent unwanted errors

if(typeof console == "undefined") {
	var console = {
		log: function () {},
		dir: function () {}
	};
}
else if(console.log == "undefined") {
	console.log = function () {};
}
else if(console.dir == "undefined") {
	console.dir = function () {};
}
	
 
$(document).ready(function() {
	
	// Handle ajax calls neatly
	$('body').ajaxStart(function() {
		$('.submitField').addClass('loading');
	});
	
	$('body').ajaxStop(function() {
		$('.submitField').removeClass('loading');
	});
			
	// Active scroll to newsitems on front page
	$("#newsitemcarousel").jcarousel({
		vertical: false,
		scroll: 1
	});
	
	// Mallistot link redirect force
	$('#mainnavi-mallistot a').click( function(e) {
		$('#Muuttovalmiit > a').trigger('click');
	});
	
	$("#newsblock").each(function(){
    	
		var maxHeight = 89; //min-height of list-items is 89 pixels
        
        $(this).find(".hiddenHeight").each(function() {
			maxHeight = Math.max(maxHeight, $(this).height());
        });

		// Set the height of list items inside newsblock
		$(this).find(".hiddenHeight").each(function() {
			var me = $(this);
			me.height(maxHeight);
			
			if(me.parent().hasClass('campaign')) {
				me.click(function(e) {
					window.location = $(me.children('a')[0]).attr('href');
				});
			}
		});
		
		var height = $('#newsblock .jcarousel-clip-horizontal').height();
		$(".jcarousel-skin-news .jcarousel-prev-horizontal").height(height);
		$(".jcarousel-skin-news .jcarousel-next-horizontal").height(height);
        
    });

	// restore visibility
	$('#newsitemcarousel').css('visibility', 'visible');
	$('.load-container').css('visibility', 'visible');
	
	// Find out if content is loaded based on url hash
	if (!fromExURL) {
		fromExURL = initialStateFromURL();
	}
	else {
		showCatalogueContent();
	}

	// Open and close functionality for #housesshowing
	$("#realestateblock a#taloesittely").click(function() {
		$("#houseshowing").show("fast");
		return false;
	});
	
	$("#houseshowing a.close").click(function() {
		$("#houseshowing").hide("fast");
		return false;
	});
	
	// Opens houseimages in fancybox
	$("a.openhouseimage").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 500
	});


	// Opens 'asiantuntijamyyjät' in fancybox
	$("a#asiantuntijamyyjat").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 500
	});
	
	// Opens 'kodinvälittäjät' in fancybox
	$("a#kodinvalittajat").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 500
	});
	
	
	$("div#javascriptwarning").css("display", "none");
		
	// links opening the nearest reseller selection
	$("a.opensellers").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 500
	});
	
	// scrolls to houseshowing
	$('a.openhouseshowing').click(function(e) {
		e.preventDefault();
		openHouseShowing();
	});
	
	// ...also after ajax fetches (should be replaced with .live() on upgrade)
	$('body').ajaxStop(function() {
		$("a.opensellers").fancybox({
			'hideOnContentClick': false,
			'frameHeight': 500
		});
		
		$('a.openhouseshowing').click(function(e) {
			e.preventDefault();
			openHouseShowing();
		});
	});
	
	// link opens the feedback form
	$("a.openfeedback").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 500,
		'frameWidth': 560
	});

	// opens news box
	$("a.openenews").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 578
	});
	
	$("a.iframe").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 578
	});
	
	// Bind this also after ajax load
	$('#container').ajaxStop(function() {
		$("a.iframe").fancybox({
			'hideOnContentClick': false,
			'frameHeight': 578
		});
	});
	
	
	/* These need to be conditionally binded as IE has some issues with change and Chrome with click */
	// seller selection ajax request for #sellerswrap
	$("#fancy_content select#sellercity").live(($.browser.msie ? "click" : "change"), function(event) {
		loadCitySellers ($(this).attr("value"));
	});
	
	/* These need to be conditionally binded as IE has some issues with change and Chrome with click */
	// seller selection ajax request for #sellerswrap
	$("#fancy_content select#site").live(($.browser.msie ? "click" : "change"), function(event) {
		loadNewSites ($(this).attr("value"));
	});
	
	// seller selection ajax request for #expertwrap
	$("#fancy_content select#expertcity").live(($.browser.msie ? "click" : "change"), function(event) {
		loadCityExperts ($(this).attr("value"));
	});
	
	
	// news item read more -link for ajax loading
	$("li.newsitem a").live("click", function(event) {
	  loadFullNewsitem($(this).parents("li.newsitem").attr("id"));
	  event.preventDefault();
	});
	// and closing the full news view
	$("div#fullnews div.close a").click(function(event) {
	  $("div#fullnews").css("display", "none");
	  event.preventDefault();
	});
		
	/*
	 * load all houses to houselist when arriving to Mallistot page,
	 * only when not arriving from external link
	 */ 

	if (!fromExURL && $('#housecategoryNavi').length > 0) {
		loadAllHouseCategories();
	}

	/* load the housecategory front page */
	$('#housecategoryNavi .category-link').live('click', function(e) {
		e.preventDefault();
		var link = $(this);
		var id = link.attr('id').split('-')[1];
		$('#housecategoryNavi .active').removeClass('active');
		link.addClass('active');
		
		var hash = '/' + link.parent('li').attr('id');
		window.location.hash = hash;
		
		resetFilter();
		loadOneCategory(id);
		updateFilter(id);
	});
	
	
	// selecting a house from house list
	$("div.housemodel").live("click", function(event) {
		var house = $(this);
		// Add parameters after hash tag in url to make a working link
		var id = house.children("span.hidden").attr("id");
		
		while(id.match("_")) {
			id = id.replace("_","/");	
		};

		window.location.hash = '/' + id;
		
		var houseId = house.attr('id').split('-')[1];
		loadOneHouse(houseId);
	});
	
	// offsetting house list 
	$("a#next, a#prev").live("click", function(event) {
		offsetHouseList($(this).attr("href"));
		event.preventDefault();
	});
	 
	// filtering houses via form
	$("form#housefilter").submit( function(e) {
		e.preventDefault();
		filterHouseList(e.target);
	});
	
	// switching which house thumbnail is shown in medium size
	$("#houseimagecarousel img").live("click", function() {
	 	if($(this).parents('ul#houseimagecarousel').hasClass('new-sites-carousel')) {
	 		enlargeHouseThumbnail($(this).attr("src"), true);
	 	} else {
			enlargeHouseThumbnail($(this).attr("src"), false);
		}
	});
	
	
	// all paragraphs containing italic text are made italic (italic portion itself is shown as green)
	$(".contentcell i").parents("p").addClass("caption");
	
	
	// regular content cell image carousels (showing 1 at time) 
	$("ul.imagecarousel").jcarousel({
		vertical: false,
		scroll: 1
    });

	// store default content at beginning, no need to fetch via AJAX request later
	allcategories_maincontent = $("#housecataloguecontent").html();
	
	$("#houseshowing .sellerswrapper ul li:nth-child(3n)").addClass('bottom-part');
	
	updateShareLink();
	//showHideRealestateblock();
	
	// newsblock is hidden initially to prevent flickering
	//$("#newsblock").animate({opacity: 1}, 500);	
		
	
	$('a[href="#taloesittely"]').live('click', function() {
		$("#houseshowing").show();
	});
	
	$('.new-sites-filter #categoryfilter').bind('change', function(e) {
		updateNewHousesFilter($(this));
	});
	
	// Initialize google maps
	if($('#googleMapsBox').length > 0) {
		initializeMap();
	}
	
	$('.imagecarousel-autoplay').jcarousel({
		vertical: false,
		scroll: 1,
        auto: 2,
        wrap: 'both',
        initCallback: mycarousel_initCallback
	});
	

	/*
	 *	Image gallery
	 */ 
	
	// We only want these styles applied when javascript is enabled
	//$('div.navigation').css({'width' : '300px', 'float' : 'left'});
	//$('div.content').css('display', 'block');

	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.67;
	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	

	// Initialize Advanced Galleriffic Gallery
	if($('#gallery').length > 0) {

	var gallery = $('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 12,
		preloadAhead:              10,
		enableTopPager:            false,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         true,
		playLinkText:              'Katso esityksenä',
		pauseLinkText:             'Pysäytä esitys',
		prevLinkText:              '&laquo; Edellinen',
		nextLinkText:              'Seuraava &raquo;',
		nextPageLinkText:          'Seuraavat &raquo;',
		prevPageLinkText:          '&laquo; Edelliset',
		enableHistory:             true,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 700,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
				
			// add facebook like button
			$('#facebook-like-container').html(addFacebookLike());
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		}
	});
	
	}

	/**** Functions to support integration of galleriffic with the jquery.history plugin ****/

	// PageLoad function
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
	function pageload(hash) {
		// alert("pageload: " + hash);
		// hash doesn't contain the first # character.
		if(hash) {
			$.galleriffic.gotoImage(hash);
		} else {
			gallery.gotoIndex(0);
		}
	}

	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(pageload, "advanced.html");

	// set onlick event for buttons using the jQuery 1.3 live method
	$("a[rel='history']").live('click', function(e) {
		if (e.button != 0) return true;

		var hash = this.href;
		hash = hash.replace(/^.*#/, '');

		// moves to a new page. 
		// pageload is called at once. 
		// hash don't contain "#", "?"
		$.historyLoad(hash);

		return false;
	});	
	
});

/* Iniatializes Google Maps in New Houses */
function initializeMap() {
	var address = $('p#address').text();
	var geocoder = new google.maps.Geocoder();
	
	//Find latitude and longitude
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
		var myOptions = {
		  zoom: 12,
		  center: results[0].geometry.location,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById('map_container'),myOptions);
		var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
           	});

      } else {
        	$('#map_container').html('<p class="mapError">Karttaa ei löytynyt</p>');
      }
    });	
}

/* Activate jcarousel on demand */
function activateCarousel() {
	$('.imagecarousel').jcarousel({
		vertical: false,
		scroll: 1
	});
}
	
/* updates the addThis bar sharing link */
function updateShareLink() {
	$("a.addthis_button").attr("addthis:url", window.location);
	
	/*
	 * This is needed to update addThis sharing link after Ajax calls
	 * http://joecurlee.com/2010/01/21/how-to-use-addthis-with-ajax-and-overflowauto/ 
	 */
	var script = "http://s7.addthis.com/js/250/addthis_widget.js#domready=1";
	if (window.addthis !== null && window.addthis){
	    window.addthis = null;
	}
	$.getScript( script );
}


/* open and close frontpage real estate advertisements */
function shortenRealestateAds() {	
	
	$("div.shortversion").css("display", "block");
	$("div.longversion").css("display", "none");
	
	$("div#realestateblock img").each(function() {
		$(this).attr("width", realestateimg_width/2);	
		$(this).attr("height", realestateimg_height/2);	
	});

}
function toggleRealestateAd(currentid) {
	
	var img_width = realestateimg_width;
	var img_height = realestateimg_height;
	var hideversion = "shortversion";
	var showversion = "longversion";
	
	if ($("div#" + currentid + " div.longversion").css("display") == "block")
	{
		img_width /= 2;
		img_height /= 2;
		hideversion = "longversion";
		showversion = "shortversion";
	}
	
	$("div#" + currentid + " div." + hideversion).css("display", "none");
	$("div#" + currentid + " div." + showversion).css("display", "block");
	$("div#" + currentid + " img").each(function() {
		$(this).attr("width", img_width);	
		$(this).attr("height", img_height);	
	});
}


/* extends / shortens content cell text */
function toggleExtendedContent(contentcell) {

	if ($(contentcell).children("div.extendedcontent").css("display") == "none") {
		$(contentcell).children("div.extendedcontent").css("display", "block");
		$(contentcell).children("a.readmore").text("<< Piilota");
	}
	else {
		$(contentcell).children("div.extendedcontent").css("display", "none");
		$(contentcell).children("a.readmore").text("Lue lisää >>");
	}
}

/* loads text search results via ajax call - not yet fully implemented */
function loadTextSearch() {
	
	var searchstring = jQuery.trim($("input#searchkey").val());
	
	if (searchstring == "") {
		$("div#searchresults").fadeOut("fast");
	}
	else {
		searchstring = escape(searchstring) + "*";
		ajaxloader_timeout = setTimeout ("showAjaxSearchLoader()", 200);
	
		var ajaxurl = ajaxrequest_baseurl_search + "/(SearchText)/" + searchstring + getCacheKiller();
		
		$.post(ajaxrequest_baseurl_search, { SearchText: searchstring },
	  		function(data){
	  			hideAjaxSearchLoader();
	    		$("div#searchresults").html(data);
	    		
	    		if ($("div#searchresults").css("display") == "none") {
	    			$("div#searchresults").fadeIn("fast");
	    		}
	  	}, "html");
	}
}



/* load and show house sellers for the selected city */
function loadCitySellers(cityidstr) {
	var cityid = cityidstr.replace("city_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + cityid + getCacheKiller();
	
	if (showdebug) {
		$("#fancy_content div.sellercontent").load(ajaxurl);	
	}
	else {
		$("#fancy_content div.sellercontent").load(ajaxurl + " div#sellersresponse");
	}
}

/* load and show house sellers for the selected city */
function loadNewSites(siteidstr) {
	var siteid = siteidstr.replace("site_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + siteid + getCacheKiller();

	if (showdebug) {
		$("#fancy_content div.sitecontent").load(ajaxurl);	
	}
	else {
		$("#fancy_content div.sitecontent").load(ajaxurl + " div#sellersresponse");
	}
}

/* load and show experts (kodivälittäjät) for the selected city */
function loadCityExperts(cityidstr) {
	var cityid = cityidstr.replace("city_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + cityid + getCacheKiller();
	
	if (showdebug) {
		$("#fancy_content div.expertcontent").load(ajaxurl);
	}
	else {
		$("#fancy_content div.expertcontent").load(ajaxurl + " div#sellersresponse");
	}
}


/* loads news item text via ajax call */
function loadFullNewsitem (itemidstring) {
	
	var newsitemid = itemidstring.replace("newsitem_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/full/" + newsitemid + getCacheKiller();

	if (showdebug) {
		$("#fullnews .content").load(ajaxurl);
	}
	else {
		$("#fullnews .content").load(ajaxurl + " div#fullnewsitem");
	}
		
	$("div#fullnews").css("display", "block");
}




/* Load house list via ajax request for all categories */
function loadAllHouseCategories() {
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + housesfolderid + "/(offset)/0" + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
		
	$("#houselist").load(ajaxurl, hideAjaxHouseLoader);

	// show stored main content for the whole catalogue
	$("#housecataloguecontent").html(allcategories_maincontent);
	
	updateShareLink();
}

/* Loads category front page and updates houselist with houses within category */
function loadOneCategory(catId){
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + catId + "/(offset)/0" + getCacheKiller();
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
	$("#houselist").load(ajaxurl, hideAjaxHouseLoader);
	
	ajaxurl = ajaxrequest_baseurl_view + "/full/" + catId + getCacheKiller();
	$("#housecataloguecontent").load(ajaxurl, function() {
		showCatalogueContent();
		activateCarousel();
	});

	updateShareLink();
}

/* load (ajax) and update main content area with selected house */
function loadOneHouse(houseId) {

	var ajaxurl = ajaxrequest_baseurl_view + "/full/" + houseId + getCacheKiller();
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);

	$("#housecataloguecontent").load(ajaxurl, function() {
		activateHouseImages();
		$('#house .facebook-like-container').html( addFacebookLike() );
	});
	
	updateShareLink();
	
	$(".currenthouse").removeClass("currenthouse");
	$("#hid-" + houseId).addClass("currenthouse");

}

function loadCategoryAndHouse(catId, houseId) {	
	
	/* load house list */	
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + catId + "/(offset)/0" + getCacheKiller();
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
	
	$("#houselist").load(ajaxurl, function() {
		hideAjaxHouseLoader();
		$(".currenthouse").removeClass("currenthouse");
		$("#hid-" + houseId).addClass("currenthouse");
	});
	
	$('#housecategoryNavi').find('.active').removeClass('active');
	$('#housecategoryNavi #cid-' + catId).addClass('active');
	
	
	
	/* load correct house data */
	var ajaxurl = ajaxrequest_baseurl_view + "/full/" + houseId + getCacheKiller();
		

	$("#housecataloguecontent").load(ajaxurl, function() {
		activateHouseImages();
		$('#house .facebook-like-container').html( addFacebookLike() );
	});
	
	updateShareLink();

}


/* if housepage has black box, this function changes the position of inner html (hack) */
function loadBlackBoxContent() {
	// Clear old stuff
	$("#blackboxcontainer").empty();
	
	// show black box content
	var blackboxcontent = $("#blackboxcontent").html();
	
	if (blackboxcontent !== null && blackboxcontent.length > 0) {
		$("#blackboxcontainer").html(blackboxcontent);
		$("#blackboxcontent").html("");
	}
	
	// Also get the map
	$("#mapboxcontainer").empty();
	if($('#googleMapsBox').length > 0) {
		initializeMap();
		$("#mapboxcontainer").html($("#googleMapsBox").html());
		$("#googleMapsBox").html('');
	}
}



// removes .hidden class from #housecataloguecontent
function showCatalogueContent() {	
	$("#housecataloguecontent").removeClass("hidden");
}

// adds .hidden class from #housecataloguecontent
function hideCatalogueContent() {
	$("#housecataloguecontent").addClass("hidden");
}

/* Does ajax request for next/prev links (using url of href attribute) in house list*/
function offsetHouseList(url) {
	var ajaxurl = url + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);

	if (showdebug) {
		$("#houselist").load(ajaxurl, function() {
			hideAjaxHouseLoader();
			if(fromExURL) {
				var houseNum = getHouseNum();
				updateSelectedHouseNum(houseNum);
			}
		});
	}
	else {
		$("#houselist").load(ajaxurl + " div#houselistcontent", function() {
			hideAjaxHouseLoader();
			if(fromExURL) {
				var houseNum = getHouseNum();
				updateSelectedHouseNum(houseNum);
			}
		});
	}
}

// parses housenumber from url hash
function getHouseNum() {
	var hash = window.location.hash;
	var segments = hash.split("/");
	if(segments.length - 1 > 1) {
		return segments[segments.length - 1];
	}
	
	return false;
}

// updates 'currenthouse' in houselist if found one
function updateSelectedHouseNum(houseNum) {
	if (houseNum !== false) {
		$("div.currenthouse").removeClass("currenthouse");
		$("div#house_" + houseNum).addClass("currenthouse");
	}
}

/* fetches houses matching the filter via ajax request */
function filterHouseList () {
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + $("form#housefilter #categoryfilter").val();

	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);

	$("form#housefilter select.buildurl").each (function() {
		ajaxurl += "/(" + $(this).attr("name") + ")";
		ajaxurl += "/" + $(this).val();
	});
	
	ajaxurl += getCacheKiller();
	$("#houselist").load(ajaxurl, hideAjaxHouseLoader);
}


/* when house content loaded, activate the image plugins */
function activateHouseImages() {
	$("a#viewfullimage").fancybox();
	
	showCatalogueContent();
	
    $("ul#houseimagecarousel").jcarousel({
		vertical: false,
		scroll: 1
    });
	
	
    hideAjaxHouseLoader();
}

/* swaps the thumbnail shown in the medium image view */
function enlargeHouseThumbnail(thumburl, newsites) {

	if(newsites) {
		var mediumurl = thumburl.replace("_house_thumb", "_house_medium_newsites");
		var fullurl = thumburl.replace("_house_thumb", "_house_full_newsites");
	} else {
		var mediumurl = thumburl.replace("_house_thumb", "_house_medium");
		var fullurl = thumburl.replace("_house_thumb", "_house_full");
	}

	$("img#housemediumimage").attr("src", mediumurl);
	$("a#viewfullimage").attr("href", fullurl);
}


/* show and hide the ajax loader animations */
function showAjaxSearchLoader()
{
	$("input#searchkey").addClass("ajaxloader");
}
function hideAjaxSearchLoader()
{
	clearTimeout(ajaxloader_timeout);
	$("input#searchkey").removeClass("ajaxloader");
}

function showAjaxHouseLoader()
{
	$("div#housecategorynavi").addClass("ajaxloader");

}
function hideAjaxHouseLoader()
{
	clearTimeout(ajaxloader_timeout);
	$("div#housecategorynavi").removeClass("ajaxloader");
}

//
function showHideRealestateblock() {
	// hack to hide realestateblock from other pages than mallistot front page
	// check url
	var url = location.href;
	var flag_mallistot = false;
	url = url.split("/");
	
	$.each(url, function(index, value) {
		value = value.toLowerCase();
		if(value.indexOf('mallistot') === 0) {
			flag_mallistot = true;		
		}
	});
	
	if(flag_mallistot) {
		// hide in mallistot pages, except the front page
		if(location.hash.length > 0) {
			$("#realestateblock").addClass('hidden');
		} else {
			$("#realestateblock").removeClass('hidden');
		}
	}  else {
		// show in other pages
		$("#realestateblock").removeClass('hidden');
	}
}


// generates unique part to ajax request URLs, in order to prevent IE caching
function getCacheKiller() {
	var uniquepart = "/(preventcache)/" + Math.floor(Math.random()*1000000001);
	return uniquepart;
}

/* checks if there's a hash link when page loads and loads the house from the link 
 * 
 * returns true, if hash is modified and content loaded based on it
 */
function initialStateFromURL() {
	var initialHash = window.location.hash,
		url = '',
		uudiskohde = ($('.new-sites-filter').length > 0) ? true : false,
		galleria = ($('#gallery').length > 0) ? true : false
		;

	if( galleria ) {
		return;
	}
	
	// Open houseshowing when linking from other pages than frontpage
	if(initialHash === '#taloesittelyt') {
		openHouseShowing(true);
		return;
	}
		
	// not coming from external source or url ends with "/"
	if(initialHash.length === 0 || initialHash.charAt(initialHash.length - 1) == "/") { 
		// error in url hash, redirect to root
		if (initialHash.length > 0) {
			url = location.href;
			url = url.substr(0, url.indexOf("#"));
			window.location = url;

			return false;
		}
		
		showCatalogueContent();
		return false; 
	}


	var segments = initialHash.split("/");
	var numOfSegments = segments.length - 1;

	// Find out which category page should be loaded and pass it along
	var catName = segments[1];
	var catNum = 0;
	var naviItem = $('#housecategoryNavi #' + catName);
	
	// Test the existence of the named category
	if(naviItem.length > 0) {
		catNum = naviItem.children('.category-link').attr('id').split('-')[1];
	}

	// The hash is not found (error in hash), load root
	if (catNum === 0 && !uudiskohde) {
		redirectToMallistotRoot()
		return false;
	}

	if(!uudiskohde) {
		updateFilter(catNum);
	}
	
	// Load just the category
	if (numOfSegments == 1 && !uudiskohde) {
		loadOneCategory(catNum);
		//update active navigation
		$('#housecategoryNavi a.active').removeClass('active');
		$('#cid-' + catNum).addClass('active');
	} else if (numOfSegments > 1) {
		// Load category houselist and defined house
		// Parse the house node number and pass it along to load one house data
		var houseId = parseInt(segments[numOfSegments]);
		if( (typeof houseId) === 'number' && isFinite(houseId) ) {
			if(uudiskohde) {
				loadAllHouseCategories();
				loadOneHouse(houseId);
				resetFilter();
			} else {
				loadCategoryAndHouse(catNum, houseId);
			}
		} else {
			redirectToMallistotRoot();
		}
	}

	return true;
	
}

/* Redirect to root */
function redirectToMallistotRoot() {
	var url = location.href;
	url = url.substr(0, url.indexOf("#"));
	window.location = url;	
}

/*
	Hack to get IE7 to obey z-indexes properly
*/
function isIE() {
    if(navigator.userAgent.match(/MSIE \d\.\d+/)) {
        return true;
    }
    return false;
}


/* function for flash banner to open househowing */
function openHouseShowing() {
	
	$("#houseshowing").show("fast");

	// animate scroll to the link
	$('html, body').animate({
		scrollTop: $("#taloesittely").offset().top
		}, 500, function () {
		
		});

	return false;
}

/* function for flash banner to open housesellers */
function openSellersList() {
    $("#supportivenavi .opensellers").trigger('click');
    return;
}


/* Updatest the new house main page on dropdown change */	
/* Currently not in use
function updateNewSite(categoryid) {

	ajaxurl = ajaxrequest_baseurl_view + "/full/" + categoryid + getCacheKiller();

	if (showdebug) {
		$("#housecataloguecontent").load(ajaxurl, function() {
		});
	}
	else {
		$("#housecataloguecontent").load(ajaxurl + " div#housecategory", function() {
		});
	}
}
*/

/* updates the category filter's category field */
function updateFilter(catId) {
	var catName = $('#housecategoryNavi #cid-' + catId).parent().attr('id');
	var temp = $('#tempfilter');
	var filter = $('#housefilter #categoryfilter');
	$('#housefilter .temp').remove();
	filter.show(); // make sure it's visible

	// update the original filter
	if( temp.children().length < 1 ) {
		temp.html(filter.children().clone());
	} else {
		filter.html(temp.children().clone());
	}
	
	filter.children().each( function() {
		var classes = $(this).attr('class').split(' ');
		if( $.inArray('parent-' + catName, classes) && $.inArray('all', classes) )  {
			$(this).remove();
		}
		
		// update the all filter value
		filter.children('.all').val(catId);	
		
	});
	
	// If there's only one option, show it as plain text
	if( filter.children().length == 2) {
		filter.hide();
		filter.after('<span class="temp">' + filter.children().last().html() + '</span>')
	}
}

/* updates new houses filter */
function updateNewHousesFilter(target) {
	var catId = target.val();
	var temp = $('#tempfilter');
	var filter = $('#housefilter #condominium');
	
	$('#housefilter .temp').remove();
	filter.show(); // make sure it's visible
			
	if(target.hasClass('all-' + catId)) {
		if(temp.children().length > 0) {
			filter.html(temp.children().clone());
		}
		return;
	}
	
	// update the original filter
	if( temp.children().length < 1 ) {
		temp.html(filter.children().clone());
	} else {
		filter.html(temp.children().clone());
	}
	
	filter.children().each( function() {
		var classes = $(this).attr('class').split(' ');
		if( $.inArray('catid-' + catId, classes) && $.inArray('all', classes) )  {
			$(this).remove();
		}	
		
	});
	
	// If there's only one option, show it as plain text
	if( filter.children().length == 2) {
		filter.hide();
		filter.after('<span class="temp"><span>' + filter.children().last().html() + '</span></span>');
	}
	

}

/* reset the housefilter */
function resetFilter() {
   if(document.forms['housefilter']) {
        document.forms['housefilter'].reset();
    }
}


/*
	Creates an iframe facebook like button
	
	Params
		- url - optional - The url to be liked. Defaults to current pages url
		- settings - optional - Override default settings
	
	Return - html - iframe code for facebook like button
*/
function addFacebookLike(url, settings) {
	if(typeof url === 'undefined') {
		var url = window.location;
	}
	
	url = escape(url);
		
	var config = {
		'app_id' : 213185515404297,
		'send' : false,
		'layout' : 'button_count',
		'width' : 100,
		'show_faces' : false,
		'action' : 'like',
		'colorscheme' : 'light',
		'font' : 'trebuchet+ms',
		'height' : 21
	}
	
	$.extend(config, settings);
	
	var html = '<iframe scrolling="no" style="overflow:hidden;height:' + config.height + 'px;width:' + config.width + 'px;" frameborder="0" allowTransparency="true" ';
	html += 'src="http://www.facebook.com/plugins/like.php?';
	html += 'href=' + url;
	html += '&app_id=' + config.app_id;
	html += '&send=' + config.send;
	html += '&layout=' + config.layout;
	html += '&width=' + config.width;		
	html += '&show_faces=' + config.show_faces;	
	html += '&action=' + config.action;
	html += '&colorscheme=' + config.colorscheme;
	html += '&font=' + config.font;
	html += '&height=' + config.height;
	
	html += '"';
	html += '></iframe>';
	
	return html;
}

/*
	Callback function for slideshow in introblock

	Params
		- carousel - required - jCarousel object

	Return - null
*/
function mycarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
}

/*
	Callback function for the frontpage flash to open a pdf
	Return - null
*/
function openAttachment() {
	var attachmentUrl = $('#attachment-url').attr('href');
	if(attachmentUrl) {
		window.top.location = attachmentUrl;
	}
}

