// --------------------------------------------------
// body onload
// --------------------------------------------------
$(document).ready(function() {
	fixCroppedImages();
	fixButtons();

	$('a').bind('focus.blur',	function(){
									$(this).blur();
								});
});



// --------------------------------------------------
// fixCroppedImages()
// --------------------------------------------------
function fixCroppedImages(){
	setTimeout( function(){

		$('.crop').each(function(){

			// doel afmeting
			cropW	= $(this).width();
			cropH	= $(this).height();

			// div maken met doel afmeting
			$(this).wrap('<div></div>')
			.parent().css({
				width:		cropW,
				height:		cropH,
				overflow:	'hidden'
			})
			.css({
				border: 	'1px solid #c5c5c5'
			})
			.end()

			// bestaande width en height verwijderen
			.removeAttr('height')
			.removeAttr('width')
			.removeAttr('class');

			// nieuwe afmeting berekenen
			aspect	= $(this).width() / $(this).height();
			if(aspect < 1){
				newW	= cropW;
				newH	= cropW / aspect;
			} else {
				newH	= cropH;
				newW	= cropH * aspect;
			}

			newW		= Math.round(newW) + 16;
			newH		= Math.round(newH) + 16;

			wDiff	= newW - cropW;
			hDiff	= newH - cropH;

			$(this).css({
				width:		newW,
				height:		newH,
				marginLeft:	wDiff/-2,
				marginTop:	hDiff/-2,
				overflow:	'hidden'
			});
		});

	}, 600);
}

// --------------------------------------------------
// fixButtons()
// --------------------------------------------------
function fixButtons(){
	setTimeout( function(){

		// zoek:
		// <a href="#link_url" class="custom_button">link_name</a>
		// vervang door:
		// <div class="clear"><a class="button" href="#link_url" onclick="this.blur();"><span>link_name</span></a></div>

		$('.custom_button').each(function(){

			$(this)
				.wrap('<div></div>')
					.parent()
						.addClass('clear')
					.end()
					.removeAttr('class')
					.addClass('button')
					.html('<span>'+$(this).html()+'</span>');

			/*ioBase 	= $(this).attr('href').indexOf(URL_BASE);
			if( io >= 0 ){
				$(this).attr('target', '_self')
			} else {
				$(this).attr('target', '_blank')
				$(this).css('background-image','url("img/bg_button_a_extern.gif")')
			}*/

			if ($(this).attr('target')=='_blank') {
				$(this).css('background-image','url("img/bg_button_a_extern.gif")')
			}

			// Fix voor rss links
			if ($(this).parents('div.clear').siblings('p.socialmedia').length==1) {
				$(this).parents('div.clear').siblings('p.socialmedia').appendTo($(this).parents('div.clear'))
				.css({
					marginTop: 24
				});
			}

			if ($('#bin_1884').length==1 && $('#bin_1884 div.clear a.noindex').length==0) {
				$('#bin_1884')
				.find('div.clear > p.socialmedia')
				.before('<a href="http://www.vvvzuidlimburg.nl/" class="noindex" target="_blank" style=""><img src="img/liefde_voor_het_leven.gif" style="margin-top: 3px; margin-left: 5px;" /></a>')
				.css('margin-top', '5px');
			}
		});

		$('#col_1, #col_2, #col_3').trigger('fixHeight');

	}, 600);
}



// --------------------------------------------------
// url_encode(str)
// --------------------------------------------------
function url_encode(str){
	str		= escape(str);
	str		= str.replace(/\+/g, "%2B");
	str		= str.replace(/\//g, "%2F");

	return str;
}

// --------------------------------------------------
// url_decode(str)
// --------------------------------------------------
function url_decode(str){
	str		= unescape(str);
	str		= str.replace(/%2B/g, '+');
	str		= str.replace(/%2F/g, '/');

	return str;
}

// --------------------------------------------------
// form_to_funda_url(form)
// --------------------------------------------------
function form_to_funda_url(form){

	// funda URL opbouwen
	// --------------------------------------------------

	// form elementen
	var locatie			= form.locatie.value;
	var straal			= form.straal.value;
	var prijs_van		= form.prijs_van.value;
	var prijs_tot		= form.prijs_tot.value;

	// basis url
	var funda_url		= 'http://www.funda.nl/koop/';

	// locatie
	if(locatie){
		locatie			= locatie.replace(/ /g, "-");
		locatie			= locatie.toLowerCase();
		funda_url		+= locatie +'/';
	}

	// straal
	if(straal>0){
		funda_url		+= '+' + straal +'km/';
	}

	// prijs range
	if(!prijs_tot){
		var prijs_range		= prijs_van +'+';
	} else {
		var prijs_range		= prijs_van +'-'+ prijs_tot;
	}
	if(prijs_range){
		funda_url		+= prijs_range +'/';
	}


	return funda_url;
}

// --------------------------------------------------
// funda_zoek(funda_url)
// --------------------------------------------------
function funda_zoek(funda_url){

//	SWFAddress.setValue('funda_url='+url_encode(funda_url));

	$.ajax({
		url:		'inc/funda_zoekform.php',
		data:		{funda_url: funda_url},
		cache:		false,
		success:	function(html){
						$("#funda_zoekform_result")
							.html(html)
								.parent()
									.parent()
										.css('overflow', 'visible')
										.css('height', '');

						fixCroppedImages();
					},
		error:		function(html){
						$("#funda_zoekform_result").html('Er ging iets mis...');
					}
	});

	return false;

}

// --------------------------------------------------
// funda_woning_detail(funda_url)
// --------------------------------------------------
function funda_woning_detail(funda_woning_id, funda_woning_locatie){

//	SWFAddress.setValue('funda_woning_id='+url_encode(funda_woning_id)+'&funda_woning_locatie='+funda_woning_locatie);

	$.ajax({
		url:		'inc/funda_woningdetail.php',
		data:		{woning_id: funda_woning_id, intern_extern: funda_woning_locatie},
		cache:		false,
		success:	function(html){
						$("#funda_zoekform_result").html(html);
						fixCroppedImages();
						window.scroll(0,0);
					},
		error:		function(html){
						$("#funda_zoekform_result").html('Er ging iets mis...');
					}
	});

	return false;
}

// --------------------------------------------------
// function preload_image(image_id, image_src)
// --------------------------------------------------
function preload_image(image_id, image_src){

	if( $("#"+image_id).attr("src") != image_src ){

		$("#"+image_id)

			.load(function(data){
				$(this).fadeIn("fast");
			})
			.fadeOut("fast")
			.attr('src', image_src);

	}

}

// --------------------------------------------------
// function initPositions()
// --------------------------------------------------
function initPositions() {

	$('div.bin').each(function() {
		// Sortable data
		$(this).data('widthStart', $(this).width());
		$(this).data('widthCurrent', $(this).width());
		$(this).data('overlapped', false);

		// Main data
		$(this).data('column', parseInt($(this).parent().attr('id').substring($(this).parent().attr('id').length-1)));
		$(this).data('row', parseInt($(this).parent().children().index($(this))));
		$(this).data('id', parseInt($(this).attr('id').replace(/bin_/, '')));
	});
}

// --------------------------------------------------
// function fixPosition()
// --------------------------------------------------
function fixPosition() {
	// Init vars
	var spanningBins	= new Array(); // Bins that spanned
	var spannedBins		= new Array(); // Bins that are moved because of span
	var spannedCols		= new Object(); // Columns that are being overlapped by spanning bins, for IE6 mainly
	var gTopCorrection 	= 2; // Dunno why, but top !=0, check later

	var oldSpan			= 0;
	var oldCol			= 0;

	// Get all bins which span multiple columns
	$('div.bin').each(function() {
		var cw 		= parseInt($(this).data('widthCurrent'));
		var span	= (cw-(cw%colWidth))/colWidth;
		$(this).data('span', span);
		if (span>1) {
			// Reset the spanning, since we are in a new column
			if (oldCol!=$(this).data('column')) {
				oldSpan = 0;
			}

			// Log bin
			spanningBins.push($(this));

			// Store column
			if (span>oldSpan) {
				spannedCols[$(this).data('column')] = span;
				oldSpan = span;
				oldCol	= $(this).data('column');
			}
		}
	});

	if ($.browser.msie && $.browser.version==6) {

		for (i in spannedCols) {
			if (i=='find') continue;

			var span	= parseInt(spannedCols[i]);
			var start 	= parseInt(i)+1;
			var end		= parseInt(i) + (span - 1);
			var banPos	= end + 1;

			for (j=start;j<=end;j++) {

				$('#col_'+j).css('margin-left', -((colWidth*(banPos-j)) + ((banPos-j-1)*colMargin) ));
			}
		}
	}

	if (spanningBins.length>0) {
		// Loop through them
		for (i in spanningBins) {
			if (i=='find') continue;

			var currDiv	= spanningBins[i];

			// Get the divs that are overlapped, thus should be moved
			// Calculate starting point & height of current div
			var position	= $(currDiv).position();
			var realTop		= position.top + parseInt($(currDiv).css('margin-top'));
			var top			= Math.round(realTop/gridHeight) - gTopCorrection;
			var height		= Math.round($(currDiv).height()/gridHeight);

			/*console.log('top spanning: '+top);
			console.log('height spanning: '+height);*/

			// Get column and span data
			var start		= parseInt($(currDiv).data('column')) + 1;
			var end			= start + parseInt($(currDiv).data('span')) - 2;

			// Get divs in other columns, that are overlapped
			for(i=start;i<=end;i++) {

				// Insert spacer div at the location of overlapment

				//$('#col_'+i).

				var prevHeight	= 0;

				$('#col_'+i).children('div.bin').each(function() {
					// Get top and height of the current div
					var tmpPosition		= $(this).position();
					var tmpRealTop		= tmpPosition.top + parseInt($(this).css('margin-top'));
					var tmpTop			= Math.round(tmpRealTop/gridHeight) - gTopCorrection;
					var tmpHeight		= Math.round($(this).height()/gridHeight);

					// If the bin start at the same height or overlaps the space reserved
					// for out expanding bin, then move down
					if ($(this).data('overlapped') || tmpTop==top || (tmpTop<top && tmpTop+tmpHeight>top)) {
						var topMargin	= (((top+height)*gridHeight)-prevHeight)+binMargin;
						$(this).css('margin-top', topMargin);
						$(this).data('overlapped', true);
						spannedBins.push(this);
					}
					// Store the height for the next loop
					prevHeight		= ((tmpTop + tmpHeight)*gridHeight);
				});
			}

		}
	}

	/*console.log('spannedBins');
	console.log(spannedBins);*/

	$('div.bin').each(function() {
		if (spannedBins.length==0 || $.inArray(this, spannedBins)==-1) {
			$(this).css('overlapped', false);
			$(this).css('margin-top', 0);
		}
	});
}















/*
function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = e.contentDocument.body.offsetHeight + 35;
	} else {
		e.height = e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}

if (document.getElementById && document.createTextNode){
 addEvent(window,'load', doIframe);
}
*/
