
var debug = function (msg) {
  console.log(msg);
  return this;
};


var vuid=0;
var uid = function(){
	return vuid++ ;
}

//make objects same height
var make_same_height = function(selector){
	var max_height = 0;
	$(selector).each(function(){
		if($(this).height() > max_height){
			max_height = $(this).height();
		}
	});
	$(selector).height(max_height);	
}


//emulate popup function...
var popWindow = function(u,w,h,popEl){
	if(!popEl){
		e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
		if(e == 'png' || e == 'gif' || e == 'jpg')
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><img src=\""+ u +"\" width=\"" + w + "\" height=\"" + h + "\" border=\"0\" /></div>",{overlay:20});
		else
			popEl = $("<div class=\"popWindowDiv\" style=\"display:block;\"><iframe src=\""+ u +"\"  width=\"" + w + "\" height=\"" + h + "\" border=\"0\" frameborder=\"0\"></iframe></div>",{overlay:20});
	}
	popEl.modal({
			onOpen: function (dialog) {
						dialog.data.show();
						//dialog.data.addClass('alert');
						dialog.container.css('height','auto');
						dialog.overlay.fadeIn('normal', function () {
							dialog.container.show('normal', function () {
								//dialog.data.slideDown('normal'); // See Other Notes below regarding
														   // data display property and
														   // iframe details
							});
						});
					},
			onClose: function (dialog) {
						//dialog.data.slideUp('normal', function () {
						  dialog.container.hide('normal', function () {
							dialog.overlay.fadeOut('normal', function () {
							  $.modal.close(); // must call this to have SimpleModal
											   // re-insert the data correctly and
											   // clean up the dialog elements
							$('#alert').remove();
							});
						  });
						//});
					}
	});
	$("#modalContainer").css('width',w).css('margin-left',(w / 2) * -1).css('height',h).css('margin-top',(h / 2) * -1); 
}


//draw icons
var drawicons = function(){
	var files = new Array('ai','avi','flv','bmp','cs','dll','doc','exe','dmg','fla','gif','jpg','js','mdb','pdf','png','ppt','rdp','txt','vsd','xls','xlsx','xml','zip');
	$("a[href]").not("a[href$=php],a[href$=html],.no-icon,.noicon").each(function(){
		if($.trim($(this).text())){
			p = $(this).attr("href").split('.');
			e = p[p.length - 1].toLowerCase();
			for(i in files)
				if(files[i] === e)
					$(this).addClass('inline_icon icon_' + e);
		}
	});
}

//new confirm dialog
function confirm(message, callback) {
	$('#alert').remove();
	o = $('<div id="alert" class="clear confirm"><span class="message"></span><br /><span class="no simplemodal-close button medium gray">Annuleer</span> <span class="yes button medium gray">Okay</span></div>');
	//o.css('display','none').appendTo('body');

	o.modal({
		//closeHTML:"<a href='#' title='Close' class='modal-close'>x</a>",
		//position: ["20%",],
		//overlayId:'confirm-overlay',
		//containerId:'confirm-container', 
		onOpen: function (dialog) {
					dialog.data.show();

					w = 400;
					h = $('.message', dialog.data[0]).height();
					$("#modalContainer").css('width',w).css('margin-left',(w / 2) * -1).css('height',h).css('margin-top',(h / 2) * -1); 

					//dialog.data.addClass('alert');
					dialog.container.css('height','auto');
					dialog.overlay.fadeIn('normal', function () {
						dialog.container.show('normal', function () {
							//dialog.data.slideDown('normal'); // See Other Notes below regarding
													   // data display property and
													   // iframe details
						});
					});
				},
		onClose: function (dialog) {
					//dialog.data.slideUp('normal', function () {
					  dialog.container.hide('normal', function () {
						dialog.overlay.fadeOut('normal', function () {
						  $.modal.close(); // must call this to have SimpleModal
										   // re-insert the data correctly and
										   // clean up the dialog elements
							$('#alert').remove();
						});
					  });
					//});
				},
		onShow: function (dialog) {
			$('.message', dialog.data[0]).append(message);


			// if the user clicks "yes"
			$('.yes', dialog.data[0]).click(function () {
				// close the dialog
				$.modal.close();
				$('#alert').remove();

				// call the callback
				if ($.isFunction(callback)) {
					setTimeout(function(){callback.apply()},1000);
				}
			});
		}
	});
}


var foundOnloadAlerts = new Array();
var alert = function(str){
	foundOnloadAlerts[foundOnloadAlerts.length] = str;
}


$(document).ready(function(){

	//change read more links.
	$("a").each(function(){
		a = $(this).text().match(/lees (meer|verder).*/i);
		b = $(this).text().match(/.*terug$/i);
		if((a && a.length) || (b && b.length)){
			$(this).text('').addClass('leesmeer');
		}
	});

	//hide blank br before modules
	$(".module_contents").each(function(){
		if($(this).prev('br').length == 1){
			$(this).prev('br').remove();
		}
	});
	
	//add some typeface...
	$('fieldset legend').addClass('typeface-js');
	
	//change all forms.
	$('.submit').addClass('button gray');
	$('.controlpanel .submit').addClass('small');

	//kill empty titles and articles
	$(".article,.title").each(function(){
		if(!$.trim($(this).text()) && !$(this).find('img,object,embed').length){
			$(this).remove();
		}
	});
	


	if($('.photoalbum_module').length){
		$('.photoalbum_module .added').remove();
		$('.photoalbum_module .photoalbum_thumbs').parents('.article').find('div.article,div.title').remove();
	}
	
	
	//kill image movement
	$('.photoalbum_module img').addClass('no-top-img');
	
	//move first image
	$('.article > div.content').each(function(){
		o = $(this).find('img:eq(0),#mapsearch_1').not('.no-top-img');
		if(o.parent().is('a')){
			o = o.parent();
		}else{
			u = o.parent().find('.leesmeer').attr('href');
			if(u)
				o = o.wrap('<a href="' + u + '"></a>').parent();
		}
		o.prependTo($(this).parents('.article')).wrap('<div class="image clear"></div>');
		$(this).after($(this).find('a.leesmeer'));
	});

	//give every link to a file an icon.
	drawicons();


	//change photoalbum module
	$(".photoalbum_module .set,.photoalbum_module .photoalbum_thumb,a[href*='module=photoalbums']").click(function(e){
		e.preventDefault();
		
		var ui;
		
		//last record set
		var lastPhotoData;
		
		//rebuild JSON uri
		if($(this).attr('href')){
			var photoJsonUri = $(this).attr('href') + '&ajax=true';
		}else{
			var photoJsonUri = $(this).find('a:eq(0)').attr('href') + '&ajax=true';
		}
		photoJsonUri = photoJsonUri.replace(/^.*module=photoalbums&/,'/modules/photoalbums/index.php?');

		var fillPhotoTemplate = function(){
			//fill template
			w = lastPhotoData['dimensions'][0];
			h = lastPhotoData['dimensions'][1];
			ui.find('.image').width(w).height(h).css('background-image','url(/' + lastPhotoData['photo']['path'] + ')');
			i = lastPhotoData['photo']['info'];
			m = i.match(/^(www[.]|)([a-z0-9\-]+[\.][a-z]{2,3})$/i);
			if(m && m.length){
				i = i.replace(/^(www[.]|)([a-z0-9\-]+[\.][a-z]{2,3})$/i,'<a href="http://$2" target="_blank">$2</a>');
			}
			ui.find('.info').html(i);				
		}

		//get first time album data and init UI
		$.getJSON(photoJsonUri,function(data){
			lastPhotoData = data;

			//build template in DOM
			ui = $('<div class="albumpopup"></div>').append('<span class="prev_photo"></span><span class="next_photo"></span><div class="image_container"><div class="image"></div><div class="info"></div></div><div class="project_bar clear"><span class="prev_proj button gray medium">&laquo;vorig project</span> <span class="next_proj button gray medium">volgend project&raquo;</span></div>');
			
			//fill template
			fillPhotoTemplate();
			
			//events
			ui.find('.next_photo').click(function(){
				u = '';
				if(lastPhotoData['set_data']){
					u = photoJsonUri = photoJsonUri.replace(/albumID=[0-9]+/,'albumID=' + lastPhotoData['set_data']['next_album']['ID']);
				}
				if(lastPhotoData['next']){
					u = photoJsonUri + '&photoID=' + lastPhotoData['next'];
				}
				if(u){
					$.getJSON(u,function(data){
						lastPhotoData = data;
	
						//fill template
						fillPhotoTemplate();
					});
				}
			});
			ui.find('.next_proj').click(function(){
				if(lastPhotoData['set_data']){
					lastPhotoData['next'] = null;
				}
				ui.find('.next_photo').trigger('click');
			});

			ui.find('.prev_photo').click(function(){
				u = '';
				if(lastPhotoData['set_data']){
					u = photoJsonUri = photoJsonUri.replace(/albumID=[0-9]+/,'albumID=' + lastPhotoData['set_data']['prev_album']['ID']);
				}
				if(lastPhotoData['prev']){
					u = photoJsonUri + '&photoID=' + lastPhotoData['prev'];
				}
				if(u){
					$.getJSON(u,function(data){
						lastPhotoData = data;
	
						//fill template
						fillPhotoTemplate();
					});
				}
			});
			ui.find('.prev_proj').click(function(){
				if(lastPhotoData['set_data']){
					lastPhotoData['prev'] = null;
				}
				ui.find('.prev_photo').trigger('click');
			});
			
			//pop it
			popWindow('',800,610,ui);

		});
		
		return false;
	}).find('.name').addClass('typeface-js');
	
	
	//show container after loading dom
	$('#container').css('display','block');						   

	//make articles same height
	//if($(".home").length){
		make_same_height("#right .articles .article.single > .content,#right .articles .article.double > .content");
	//}

	//change all popups...
	var img = new Array();
	$(".article a").each(function(){
		i = 0;

		//change all onclick popups
		if($(this).attr('onclick')){
			i = $(this).attr('onclick').toString().indexOf("dow.open(this.href,");

			if(i){
				w = 640;
				h = 480;
				
				u = $(this).attr('href');
				e = u.substring(u.lastIndexOf('.')+1).toLowerCase();
				
				if(e == 'png' || e == 'gif' || e == 'jpg'){
					var id = 'popwinlink_' + uid();
					$(this).attr('id',id);

					img[id] = new Image();
					img[id].onload = function(){
						img[id].onload = null;
						w = img[id].width;
						h = img[id].height;
	
						$("a#" + id).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");
					}
					img[id].src = u;
				}else{
					c = $(this).attr('onclick').toString();

					h = parseInt(c.match(/height=([0-9]+)/)[1]) + 25;
					w = parseInt(c.match(/width=([0-9]+)/)[1]) + 25;
	
					$(this).attr('onclick',"").addClass('popWindowLink').attr('href',"javascript:popWindow('" + u + "'," + w + "," + h + ");");				
				}
			}

		//change all movie files
		}else if($(this).attr('href') && $(this).attr('href').match(/.(flv|FLV)$/)){
			//get filename...
			u = $(this).attr('href').match(/(\/db\/.*.(flv|FLV)$)/)[1];
			$(this).addClass('popWindowLink').attr('href',"javascript:popWindow('/domains/ruig.com/video.php?file=" + u + "',320,260);");		
		}
	});
	
	
	////init typeface...
	//var detective = new Detector();
	//if(!detective.test('Avenir LT Std')){
	//
	//	var addScript2Head = function(url){
	//		var script = document.createElement( 'script' );
	//		script.type = 'text/javascript';
	//		script.src = url;
	//		$('body').append(script);
	//	}
	//	
	//	addScript2Head("/domains/ruig.com/plugins/typeface/typeface-0.15.js");
	//	addScript2Head("/domains/ruig.com/plugins/typeface/avenir.typeface.js");
	//	addScript2Head("/domains/ruig.com/plugins/typeface/avenir_roman.typeface.js");
	//	
	//	_typeface_js.renderDocument();
	//}
	_typeface_js.initialize();
	
	//my little typeface hover patch that works
	$(".typeface-js a,a.typeface-js").hover(
		function(){
			if(!$(this).hasClass('typeface-js-hover-checked')){
				$(this).wrapInner('<span class="typeface-js-normal"></span>').append($('<span class="typeface-js-hover"></span>').text($(this).text()).css('color',$(this).css('color'))).addClass('typeface-js-hover-checked');
				_typeface_js.renderDocument();
			}
			$(this).find('.typeface-js-normal').hide();
			$(this).find('.typeface-js-hover').show();
		},
		function(){
			$(this).find('.typeface-js-normal').show();
			$(this).find('.typeface-js-hover').hide();
		}
	);


	//my own alert...
	alert = function(str){
		o = $('<div id="alert"><span class="string">' + str + '</span></div>');
		o.css('display','none').appendTo('body');
		popWindow('',400,o.height(),o);
	}
	//show all found alerts
	if(foundOnloadAlerts.length > 0){
		$.each(foundOnloadAlerts,function(){
			alert(this);
		});
	}	

});


