/*
	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() {
	
	// IE7 z-index fix
	//zIndexWorkaround();
	
	// Active scroll to newsitems on front page
	$("ul#newsitemcarousel").jcarousel({
		vertical: false,
		scroll: 1
	});
	
	// Find out if content is loaded based on url hash
	if (!fromExURL) {
		fromExURL = initialStateFromURL();
	}
	else {
		alert('showCatalogueContent');
		showCatalogueContent();
	}

	// Open and close functionality for #housesshowing
	$("#realestateblock a#taloesittely").click(function() {
		$("#houseshowing").show("fast");
		$("#newhouses").hide("fast");
		return false;
	});
	
	$("#houseshowing a.close").click(function() {
		$("#houseshowing").hide("fast");
		return false;
	});
	
	// Open and close functionality for #newhouses
	/*$("#realestateblock a#uudiskohteet").click(function() {
		$("#houseshowing").hide("fast");
		$("#newhouses").show("fast");
		return false;
	});*/
	
	$("#newhouses a.close").click(function() {
		$("#newhouses").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
	});
	
	
	/* 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"));
	});
	

	$("#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() {
			$(this).parent("li").height(maxHeight);
		});
		
		// Set the height of newsblock navigation
		//24px = 2x2px border + 2x10px padding
		$(".jcarousel-skin-news .jcarousel-prev-horizontal").height(maxHeight + 24);
		$(".jcarousel-skin-news .jcarousel-next-horizontal").height(maxHeight + 24);
		
		// Set the height of heading
		$("div#newsblock h2").height(maxHeight + 24);
		
		// Set the height of newsblock
		$("div#newsblock").height(maxHeight + 24);
		 
        
    });
	
	// 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() {
	  $("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) {
		$("div#housecategorynavi").each(function(){
			loadAllHouseCategories();
		});
	}

	// clicking house category name links
	$("a.showallcategories").click(function(event) {
		window.location.hash = "";
		loadAllHouseCategories();
		event.preventDefault();
	}); 

	$("a.showonecategory").live('click', function(event) {
		// Add parameters after hash tag in url to make a working link
		var id = $(this).prev("span").attr("id");
		var i = id.indexOf("_");
		var houseCat = id.substr(i + 1);
		
		window.location.hash = "/" + houseCat;		
		loadOneHouseCategory($(this).attr("id"));
		event.preventDefault();
	});
	
	// selecting a house from house list
	$("div.housemodel").live("click", function(event) {
		
		// Add parameters after hash tag in url to make a working link
		var id = $(this).children("span.hidden").attr("id");
		
		while(id.match("_")) {
			id = id.replace("_","/");	
		};

		var hash = id.substr(id.indexOf("/", 0));
		window.location.hash = hash;

		loadOneHouse($(this).attr("id"));
	}); 
	// 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(event) {
		event.preventDefault();
		
		// Let's load the correct front page for the catelogue
		if($('#housecataloguecontent').hasClass('.new-sites-catalogue')) {
			var category = $('#condominium option:selected').attr('class').split('-')[1];
			if( !isNaN(category)) {
				updateNewSite(category);
				
				var houseCat = $('#catid-' + category).find('span').attr('id');
				window.location.hash = "/" + houseCat;
				
			} else {
				window.location = window.location.protocol + "//" + window.location.host + window.location.pathname;
			}
		}

		filterHouseList(event.target);
	});
	
	// switching which house thumbnail is shown in medium size
	$("ul#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);
		}
	});
	
	/* read more -functionality on hold at the moment 
	$(".contentcell a.readmore").live ("click", function(event) {
	  toggleExtendedContent($(this).parents("div.contentcell"));	
	  event.preventDefault();
	});
	$(".contentcell a.readless").live ("click", function(event) {
	  toggleExtendedContent($(this).parents("div.contentcell"));	
	  event.preventDefault();
	});
	*/
	
	// 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);	
		
	//hideVoteLink();
	
	$('a[href="#taloesittely"]').live('click', function() {
		$("#houseshowing").show();
	});
	
	

	/* 
	 * Dropdown functionality
	 */
	$('div.dropdown > ul').live('click', function() {
		$(this).toggleClass('open');
        
        // Hack IE7 z-index
        if(isIE()) {
	        $(this).parents().each(function(index) {
	            var p = $(this);
	            var pos = p.css("position");
	
	            // If it's positioned,
	            if(pos == "relative" ||
	               pos == "absolute" ||
	               pos == "fixed")
	            {
	                    p.addClass('on-top');
	            }
	        });
        }        
	});
	
	$('div.dropdown > ul ul.listItems li').live('click', function() {
		$(this).siblings().removeClass('active');
		$(this).addClass('active');
		$('div.dropdown > ul li.selected').text($(this).text());
	});
	
	// Close on outside click
	$(window).click(function(e) {
		if($('div.dropdown').length > 0) {
			if($('div.dropdown ul.open').length > 0	&& !$(e.target).hasClass('selected')) {			
				
				$('div.dropdown > ul').each(function(i, el) {
					$(el).removeClass('open');
				});
			}
		
			// Hack IE7 z-index
	        if(isIE()) {
				$('div.dropdown > ul').parents().each(function() { $(this).removeClass('on-top');})
	        }
		}
	});
	

	
	// Initialize google maps
	if($('#googleMapsBox').length > 0) {
		initializeMap();
	}	
});

/* 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() {
	$('ul.imagecarousel').jcarousel({
		vertical: false,
		scroll: 1
	});
}

/* hide BB competition vote button */
/*function hideVoteLink() {
	if ($.cookie('already_voted_bb')) {
		$("a.open_bbvote").css("display", "none");
	}	
}*/
	
/* 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 or selected categories */
function loadAllHouseCategories() {
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + housesfolderid + "/(offset)/0" + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
		
	if (showdebug) {
		$("#houselist").load(ajaxurl, hideAjaxHouseLoader);
	}
	else {
		$("#houselist").load(ajaxurl + " div#houselistcontent", hideAjaxHouseLoader);
	}

	// show stored main content for the whole catalogue
	$("#housecataloguecontent").html(allcategories_maincontent);
	
	updateShareLink();
	showHideRealestateblock();
	
	if(document.forms['housefilter']) {
		document.forms['housefilter'].reset();
	}
	$("a.currenthousecategory").removeClass("currenthousecategory");
	$("a.showallcategories").addClass("currenthousecategory");
}

function loadOneHouseCategory (categoryidstring) {	
		
	var categoryid = categoryidstring.replace("housecategory_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + categoryid + "/(offset)/0" + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
	
	if (showdebug) {
		$("#houselist").load(ajaxurl, hideAjaxHouseLoader);
	}
	else {
		$("#houselist").load(ajaxurl + " div#houselistcontent", hideAjaxHouseLoader);
	}	
	
	ajaxurl = ajaxrequest_baseurl_view + "/full/" + categoryid + getCacheKiller();
	
	if (showdebug) {
		$("#housecataloguecontent").load(ajaxurl, function() {
			showCatalogueContent();
			loadBlackBoxContent();
			activateCarousel();
		});
	}
	else {
		$("#housecataloguecontent").load(ajaxurl + " div#housecategory", function() {
			showCatalogueContent();
			loadBlackBoxContent();
			activateCarousel();
		});
	}
	
	updateShareLink();
	showHideRealestateblock();
	
	if(document.forms['housefilter']) {
		document.forms['housefilter'].reset();
	}

	$("a.currenthousecategory").removeClass("currenthousecategory");
	$("a#" + categoryidstring).addClass("currenthousecategory");
}



/* 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('');
	}
}

function loadCategoryAndHouse(categoryidstring, houseidstring) {	
	
	/* load house list */	
	var categoryid = categoryidstring.replace("housecategory_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/list/" + categoryid + "/(offset)/0" + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
	
	if (showdebug) {
		$("#houselist").load(ajaxurl, function() {
			hideAjaxHouseLoader();
			$("div.currenthouse").removeClass("currenthouse");
			$("div#" + houseidstring).addClass("currenthouse");
		});
	}
	else {
		$("#houselist").load(ajaxurl + " div#houselistcontent", function() {
			hideAjaxHouseLoader();
			$("div.currenthouse").removeClass("currenthouse");
			$("div#" + houseidstring).addClass("currenthouse");
		});
	}
	if(document.forms['housefilter']) {
		document.forms['housefilter'].reset();
	}
	$("a.currenthousecategory").removeClass("currenthousecategory");
	$("a#" + categoryidstring).addClass("currenthousecategory");	
	
	
	/* load correct house data */
	var houseid = houseidstring.replace("house_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/full/" + houseid + getCacheKiller();
		
	if (showdebug) {
		$("#housecataloguecontent").load(ajaxurl, function() {
			activateHouseImages();
			loadBlackBoxContent();
		});
	}
	else {
		$("#housecataloguecontent").load(ajaxurl + " div#house", function() {
			activateHouseImages();
			loadBlackBoxContent();
		});
	}
	
	updateShareLink();
	showHideRealestateblock();
	
	$("div.currenthouse").removeClass("currenthouse");
	$("div#" + houseidstring).addClass("currenthouse");

}

// removes .hidden class from #housecataloguecontent
function showCatalogueContent() {
	
	// attach script to the IN category facebook share links (BB competition)
	$("#housecataloguecontent").find("a.fb_share").each(function(){ 
		$("body").append('<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>');
	});
	
	$("#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();
	
	if (showdebug) {
		$("#houselist").load(ajaxurl, hideAjaxHouseLoader);
	}
	else {
		$("#houselist").load(ajaxurl + " div#houselistcontent", hideAjaxHouseLoader);
	}
}



/* load (ajax) and update main content area with selected house */
function loadOneHouse (houseidstring) {
	var houseid = houseidstring.replace("house_", "");
	var ajaxurl = ajaxrequest_baseurl_view + "/full/" + houseid + getCacheKiller();
	
	ajaxloader_timeout = setTimeout ("showAjaxHouseLoader()", ajaxload_waittime);
	
	if (showdebug) {
		$("#housecataloguecontent").load(ajaxurl, function() {
			activateHouseImages();
			loadBlackBoxContent();
		});
	}
	else {
		$("#housecataloguecontent").load(ajaxurl + " div#house", activateHouseImages);
	}
	

	updateShareLink();
	showHideRealestateblock();
	
	
	$("div.currenthouse").removeClass("currenthouse");
	$("div#" + houseidstring).addClass("currenthouse");
	
}

/* when house content loaded, activate the image plugins */
function activateHouseImages() {
	$("a#viewfullimage").fancybox();
	
	// link opens the bb voting form in a fancybox
	/*$("a.open_bbvote").fancybox({
		'hideOnContentClick': false,
		'frameHeight': 600,
		'frameWidth': 700
	});*/

	showCatalogueContent();
	
    $("ul#houseimagecarousel").jcarousel({
		vertical: false,
		scroll: 1
    });
	
	// for BB competition, after voting
	//hideVoteLink();
	
    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;
	var url;

	// 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 houseCat = segments[1];
	//var houseCatNum = $("#housecategorynavi #Houses_" + houseCat).next("a").attr("id");
	var houseCatNum = $('#housecategorynavi').find('span[id*=Houses_' + houseCat + ']').next("a").attr("id")
	

	// The hash is not found (error in hash)
	if (houseCatNum === undefined) {
		url = location.href;
		url = url.substr(0, url.indexOf("#"));
		window.location = url;
		
		return false;
	}
	
	// Load just the category
	if (numOfSegments == 1) {
		loadOneHouseCategory(houseCatNum);	
	} 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 houseNum = segments[numOfSegments];
		//loadOneHouse("house_" + houseNum);
		loadCategoryAndHouse(houseCatNum, "house_" + houseNum);
	}
	
	return true;
	
}

/*
	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");
	$("#newhouses").hide("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;
}

/* Query ended 20110411
function openQuery() {

	if (($.cookie('query') === null)) {
		$.cookie('query', 'true');
		$('a#webquery').trigger('click');	
	} 
}
*/


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

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

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


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