// --------------------------------------------------
// body onload
// --------------------------------------------------
$(document).ready(function() {
	fixCroppedImages();
	fixButtons();
	initCultureHighlights();

	$('a').bind('focus.blur',	function(){
									$(this).blur();
								});

	//var sRestoreHomepage = '<a class="button" style="float: right;" href="http://www.zuidlimburg.nl/inc/resetcookie.php">' +
	//							'<span>Herstel homepage</span>' +
	//						'</a>';
	//$('#sitemap').prepend(sRestoreHomepage);

	//bindManualTrack('/funda/click/zoeken/', $('#funda_zoek_form').find('input.button'));
	//bindManualTrack({category: 'Funda', action: 'Click', label: 'Zoeken'}, $('#funda_zoek_form').find('input.button'));

	$('.bin_content_href').each(function() {
		var oThis = $(this);

		oThis
		.unbind('click')
		.bind('click', function(oEvent) {
			var oThis = oThis;

			if (oEvent.target.nodeName != 'A') {
				if($(this).attr('data-target') == '_blank') {
					window.open($(this).attr('data-href'));	
				}
				else {
					window.location.href = $(this).attr('data-href');
				}
			}
		});
	});

	//if(typeof(VISITED_BEFORE) != 'undefined' && VISITED_BEFORE == false) {
	//	$('body').append('<div id="modal-firstvisit"><br/><embed class="modal-firstvisit-embed" src="http://www.youtube.com/v/ri-c_dHZYdA&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width="864" height="512"></embed></div>');
	//
	//	$('#modal-firstvisit').dialog({
	//		height: 623,
	//		width: 928,
	//		modal: true,
	//		resizable: false,
	//		draggable: false,
	//		dialogClass: 'modal-firstvisit',
	//		position: ['center', 'top'],
	//		close: function(event, ui) { this.html(''); }
	//	});
	//}
});

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;
}

function hashstate_to_funda_url(hashState) {
	var searchData = $.evalJSON(hashState);
	var funda_url = 'http://www.funda.nl';

	var afstand = searchData.afstand.replace(' ', '+');

	funda_url += '/' + searchData.type;
	funda_url += '/' + searchData.locatie;
	funda_url += '/' + afstand;
	funda_url += '/' + searchData.prijsklasse;
	funda_url += '/' + searchData.pagina + (searchData.pagina != '' ? '/' : '');

	return funda_url;
}

$(window).bind( "hashchange", function(e) {
	var funda_url = hashstate_to_funda_url($.bbq.getState("searchdata"));
	
	$.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...');
					}
	});
});


// --------------------------------------------------
// funda_zoek(funda_url)
// --------------------------------------------------
function funda_zoek(funda_url){
	var pattern = /http:\/\/www.funda.nl\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)\/([^\/]+)?/;
	var fundaData = funda_url.match(pattern);

	if (fundaData != null) {
		var sStateString = '{';

		sStateString += '"type":' + '"' + fundaData[1] + '",';
		sStateString += '"locatie":' + '"' + fundaData[2] + '",';
		sStateString += '"afstand":' + '"' + fundaData[3] + '",';
		sStateString += '"prijsklasse":' + '"' + fundaData[4] + '",';
		sStateString += '"pagina":' + '"' + (fundaData[5] == undefined ? '' : fundaData[5]) + '"';
		sStateString += '}';

		$.bbq.pushState('searchdata=' + sStateString, 2);
		$(window).trigger("hashchange");
	}

//	SWFAddress.setValue('funda_url='+url_encode(funda_url));

	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"));
						bindManualTrack({category: 'Funda', action: 'Clickout', label: 'Detailpagina'}, $("#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) {
function manualTrack(data) {
	if (typeof(pageTracker) != 'undefined') {
		//pageTracker._trackPageview(url);
		var tracked = pageTracker._trackEvent(data.category, data.action, (typeof(data.label)!='undefined') ? data.label : '');
	}
	return true;
}

//function bindManualTrack(url, selector) {
function bindManualTrack(data, selector) {

	selector
	.unbind('click.pagetrack')
	.bind('click.pagetrack', function() {
		//manualTrack(url);
		/*if (typeof(data.value)=='undefined') {
			data.value = $(this).attr('href');
		}
		*/
		manualTrack(data);
		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

			// 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;

					if (binDim.bottom < divDim.top || binDim.top > divDim.bottom) {
					} else {
						$(this).css('margin-top', divDim.bottom - topOffset);
						//console.log('being overlapped');
					}
				});
			}
		}
	}

	return;
	*/

	// Init vars
	var spanningBins	= new Array(); // Bins that span multiple columns
	var spannedBins		= new Array(); // Bins that are moved because of spanning bins
	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');
			}
		}
	});

	// Fix column margins
	if ($.browser.msie && $.browser.version=='6.0') {
		// IE6 expands column if wider bin. Therefore other columns are pushed to
		// the right. This is fixed with negative margins.

		// Loop trought columns that are moved because of spanning bins in previous column
		for (i in spannedCols) {
			if (i=='find') continue; // Skip 'find' prototype in JS Array object

			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++) {

				$('#column'+j).css('margin-left', -((colWidth*(banPos-j)) + ((banPos-j-1)*colMargin) ));
			}
		}
	}

	// Fix the bins (only if there are som spanners offcourse)
	if (spanningBins.length>0) {
		for (i in spanningBins) { // Loop trough bins that span over multiple columns
			if (i=='find') continue; // Skip 'find' prototype in JS Array object

			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; // Column where overlapping can start
			var end			= start + parseInt($(currDiv).data('span')) - 2; // Column where overlapping max can end

			// Get divs in other columns, that are overlapped
			for(i=start; i<=end; i++) {

				// Insert spacer div at the location of overlapment

				//$('#column'+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)) {
					if (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);
}
*/

function resizeBinViaIframe(binID, height) {
	$('#bin_'+binID).height('auto');
	$('#iframe_'+binID).height(height);
}

function openBinContentHref(oObject, sHref) {
	console.log(oObject);
}

function initCultureHighlights() {
	$('ul.culture-highlights').each(function() {
		var sBinId = $(this).closest('.bin').attr('id');

		$(this).cycle({
			fx: 'scrollHorz',
			timeout: 5000,
			next: '#'+sBinId+' .next-highlight',
			prev: '#'+sBinId+' .prev-highlight'
		});
	});
}
