// --------------------------------------------------
// body onload
// --------------------------------------------------
$(document).ready(function() {
	fixCroppedImages();
	fixButtons();

	$('a').bind('focus.blur',	function(){
									$(this).blur();
								});

	bindManualTrack('/funda/click/zoeken/', $('#funda_zoek_form').find('input.button'));
});

var onDemandScripts = new Array();
function loadOnDemand(scriptURL, callback) {

	// Check if script is already loaded
	if ($.inArray(scriptURL, onDemandScripts)<0) {
		// Load script
		$.getScript(scriptURL, function() {
			// Store script loading for thie page
			onDemandScripts.push(scriptURL);
			// Execute callback
			callback();
		});
	} else {
		// Execute callback
		callback();
	}
}

// --------------------------------------------------
// 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);
}

// --------------------------------------------------
// fixDots()
// --------------------------------------------------
function fixDots() {
	if (arguments[0]==undefined || arguments[0]=='') arguments[0] = $(document);

	$(arguments[0]).find('span.resizer').each(function() {
		var parent		= $(this).parents('div.bin');
		var padding		= 10;
		var imgWidth	= parseInt($(parent).find('div.bin_content td img').parent().width()) + 8; // + padding-right
		var maxWidth 	= parseInt($(parent).width()) - (2*padding) - imgWidth;
		var biggestStr 	= 0;

		// Store textNodes in array
		var tNodes	= new Object();
		tNodes		= $(this).find('a').andSelf().contents().filter(function() {
			return this.nodeType==3;
		});

		// Find longest string
		for (i in tNodes) {
			if (tNodes[i].nodeType!=3) continue;
			if (biggestStr==0 || tNodes[i].length>biggestStr.length) {
				biggestStr = tNodes[i];
			}
		}

		while (this.offsetWidth>maxWidth) {

			// Make longest smaller
			biggestStr.nodeValue	= biggestStr.nodeValue.split('...').join('');
			biggestStr.nodeValue	= biggestStr.nodeValue.substr(0, biggestStr.length-1)+'...';

			if (this.offsetWidth>maxWidth) {
				// Check if any string >= longest (in smaller state), if so resize
				for (i in tNodes) {
					if (tNodes[i].nodeType!=3) continue;
					if (tNodes[i].length>biggestStr.length) {
						tNodes[i].nodeValue = tNodes[i].nodeValue.substr(0, biggestStr.length)+'...';
					}
				}
			}
		}
	});
}

// --------------------------------------------------
// 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();
						bindManualTrack('/funda/click/lijst/', $('#funda_zoekform_result').find('a[rel="detail"]'));
					},
		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);
						manualTrack("/funda/detail/");
						bindManualTrack("/funda/click/extern/", $("#funda_table").find("a.to-funda"));
					},
		error:		function(html){
						$("#funda_zoekform_result").html('Er ging iets mis...');
					}
	});

	return false;
}

// --------------------------------------------------
// Manual page tracking functions
// --------------------------------------------------
function manualTrack(url) {
	if (typeof(pageTracker) != 'undefined') {
		pageTracker._trackPageview(url);
	}
	return true;
}

function bindManualTrack(url, selector) {

	selector
	.unbind('click.pagetrack')
	.bind('click.pagetrack', function() {
		manualTrack(url);
		return true;
	});
}


// --------------------------------------------------
// 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 topOffset		= 20; //px

	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');
			}
		}
	});

	// Fix for IE 6, when spanning it will push other columns of the screen, therefore
	// set negative margin per column
	if ($.browser.msie && $.browser.version=='6.0') {

		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) {
		for (i in spanningBins) {
			if (i=='find') continue; // Skip find prototyp in array

			var currDiv		= spanningBins[i];
			//var divDim		= currDiv.offset();
			var divDim		= currDiv.position();
			divDim.width	= parseInt(currDiv.outerWidth(true));
			divDim.height	= parseInt(currDiv.outerHeight(true));
			divDim.bottom	= divDim.top + divDim.height;
 			divDim.right	= divDim.left + divDim.width;

			var colStart	= parseInt($(currDiv).data('column')) + 1; // Next column = current column + 1,
			var colEnd		= parseInt($(currDiv).data('column')) + parseInt($(currDiv).data('span')) - 1; // Last column = current column + spanning - 1

			/*
			console.log('Colstart: '+colStart+' - '+colEnd);
			console.log('Spanning div:');
			console.log(currDiv);
			console.log(divDim);
			console.log('Spanned divs:');
			*/

			// Loopthrough colomns that are being spanned and push down bins, that conflict with this bin
			for (i=colStart;i<=colEnd;i++) {

				// Check for each bin if it should be moved
				$('#col_'+i).find('div.bin').each(function() {

					//var binDim		= $(this).offset();
					var binDim		= $(this).position();
					binDim.width	= parseInt($(this).outerWidth(true));
					binDim.height	= parseInt($(this).outerHeight(true));
					binDim.bottom	= binDim.top + binDim.height;
					binDim.right	= binDim.left + binDim.width;

					/*
					console.log($(this));
					console.log(binDim);
					*/

					if (binDim.bottom < divDim.top || binDim.top > divDim.bottom) {
					} else {
						$(this).css('margin-top', divDim.bottom - topOffset);
						//console.log('being overlapped');
					}
				});
			}
		}
	}

	return;

	/*
	// Check if any spanning bins (> 1 column)
	if (spanningBins.length>0) {
		// Loop through divs that are spanning (> 1 column)
		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-20);// + parseInt($(currDiv).css('margin-top'));
			//var top			= Math.round(realTop/gridHeight) - gTopCorrection;
			var top			= Math.ceil(realTop/gridHeight) - gTopCorrection;
			//var height		= Math.round($(currDiv).height()/gridHeight);
			//var height		= Math.round($(currDiv).outerHeight(true)/gridHeight);
			var height		= Math.ceil($(currDiv).outerHeight(true)/gridHeight);

			//*
			console.log(currDiv);
			console.log('realTop: '+realTop);
			console.log('top spanning: '+top);
			console.log('height spanning: '+height);
			//*/

			/*
			// Get column and span data
			var start		= parseInt($(currDiv).data('column')) + 1; // Start with next column
			var end			= start + parseInt($(currDiv).data('span')) - 2; // End with the column till where the div spans

			// Loop through divs 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() {

					console.log($(this));
					console.log($(this).offset());
					console.log($(this).position());

					// Get top and height of the current div
					var tmpPosition		= $(this).position();
					var tmpRealTop		= (tmpPosition.top-20);// + parseInt($(this).css('margin-top'));
					//var tmpTop			= Math.round(tmpRealTop/gridHeight) - gTopCorrection;
					var tmpTop			= Math.ceil(tmpRealTop/gridHeight) - gTopCorrection;
					//var tmpHeight		= Math.round($(this).height()/gridHeight);
					//var tmpHeight		= Math.round($(this).outerHeight(true)/gridHeight);
					var tmpHeight		= Math.ceil($(this).outerHeight(true)/gridHeight);

					console.log('tmpRealTop: ' + tmpRealTop);
					console.log('tmpTop: ' + tmpTop);
					console.log('tmpHeight: ' + tmpHeight);

					console.log('++++++++++++++++++++++');

					console.log($(this).data('overlapped'));
					console.log('top: '+top);
					console.log('prevHeight '+prevHeight);

					// 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;
						var topMargin	= (((top+height)*gridHeight) - prevHeight);// + binMargin;

						console.log('topMargin: '+topMargin);

						$(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('---------------------');
				});
			}
		}
	}

	//*
	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);
}
*/
