// (see also: js/blinkit.js!)
var minwidth=100;
var minheight=100;
var targetWidth=200;
var targetHeight=200;
var noDescription="Describe your Blink";

$(document).ready(function () {

	if (location.hash) {
		if (h=location.hash.substr(1)) {
			if (!isNaN(h)) {
				loadItem(h);
			}
		}
	}

	$(document).keydown(function(e) {
		if ( !$('.comment-box').is(':focus') ) {
			if (e.keyCode == 39) { $('#next').click(); }
			if (e.keyCode == 37) { $('#prev').click(); }
			if (e.keyCode == 27) {
				closeWhitebox();
			}
		}
	});

	initCommentWhiteBoxes();

	$('#container').delegate('.blink', 'hover', function(e) {
		if (e.type == 'mouseenter') {
			$(this).find('.social-buttons').show();
		} else {
			$(this).find('.social-buttons').hide();
		}
	});

	$(window).scroll(function() {
		if ($(this).scrollTop() > 500 ) {
			$('#scroll-to-top').show();
		} else {
	  	$('#scroll-to-top').hide();
		}
	});

	/**
	 * Close whitebox
	 */
	$('body').delegate('.overlay', 'click', function(event) {
		if ( $('.overlay').children('.reblinkbox').size() == 0 ) {
			if ( event.target == this ) {
				closeWhitebox();
				event.stopPropagation();
			}
		}
	});

});

function closeWhitebox() {
	$('.overlaybg, .overlay, .whitebox').remove();
	currBlinkID=0;
	if ($container.infinitescroll) {
		$container.infinitescroll('resume');
	}
	$('body').removeClass('noflow');
}

/**
 * Alerts
 */
function showReportAlert(itemID,currUserID) {
	$('body').prepend('<div id="alertbg"></div><div id="alertbox-container"><div id="alertbox"><div class="title">Report this Blink</div><div class="text">Please let us know what\'s wrong.</div><form id="report-item"><input type="hidden" name="itemID" value="'+itemID+'"><input type="hidden" name="cmd" value="report_item"><textarea name="motivation"></textarea><br><div class="buttons"><input type="button" value="Report" class="red" onclick="reportItem('+currUserID+')" style="margin:0 10px 0 0;"><input type="button" value="Cancel" onclick="removeReportAlert()"></div></form></div></div>');
	$('#report-item textarea').focus();
}

function removeReportAlert() {
	$('#alertbg, #alertbox-container, #alertbox').remove();
}

/**
 * Selection routines
 * http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
 */
$.fn.setCursorPosition = function(position){
  if(this.lengh == 0) return this;
  return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
  if(this.lengh == 0) return this;
  input = this[0];

  if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  } else if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }

  return this;
}

$.fn.focusEnd = function(){
	if (this.val()) {
  	this.setCursorPosition(this.val().length);
  }
}

/**
 * Forms
 */
function validateForm(formID,validators,msg) {
	var errors=0;

	$.each(validators,function(field, validator) {
		var el=$('#'+formID+" [name="+field+"]");
		var eltype=el.attr("type");
		if (eltype=="radio") {
			var val=$('#'+formID+' input:radio[name='+field+']:checked').val(); // get the value from a set of radio buttons
		} else if (eltype=="text") {
			var val=$('#'+formID+" [name="+field+"]").val();
		} else {
			alert("TODO: implement type '"+eltype+"'");
		}

		if (!validateValue(val,validator)) {
			//alert("niet goed: "+validator + " / " +field);
			errors++;
			setValidationError(field);
    } else {
			//alert("goed: "+validator + " / " +field);
    	removeValidationError(field);
    }
	});

	if (errors!==0) {
		showFormMessage(formID,msg);
	} else {
		hideFormMessage(formID);
	}

	return (errors===0);
}

function validateValue(fv,validator) {
	if (fv==undefined) { fv=''; }

	var pattern=getPatternByName(validator);
  var re = new RegExp(pattern);
  return re.test(fv);
}

function getPatternByName(patternName) {
  switch (patternName) {
    case "empty_or_email":
      return "^$|^[0-9a-zA-Z][-_0-9a-zA-Z.]*@[-_0-9a-zA-Z.]+[.][a-zA-Z]+$";
      break;
    case "empty_or_url":
      return "^$|^http[s]?://.{2,}";
      break;
    case "empty_or_time":
      return "^$|^00:00$|^[012][0-9]:[0-9][0-9]$";
      break;
    case "empty_or_date":
      return "^$|^0000-00-00$|^[12][0-9]{3}[-][01]?[0-9]-[0-3]?[0-9]$";
      break;
    case "empty_or_float":
      return "^$|[+-]?[0-9]+([.][0-9]+)?$";
      break;
    case "notempty":
      return "^.";
      break;
    case "email":
      return "^[0-9a-zA-Z][-_0-9a-zA-Z.]*@[-_0-9a-zA-Z.]+[.][a-zA-Z]+$";
      break;
    case "pagename":
      return "^[_a-z0-9]{1,50}$";
      break;
    case "username":
      return "^[_a-z0-9]{1,50}$";
      break;
    case "pass":
      return "^[a-zA-Z0-9 ]{3,20}$";
      break;
    //dd-mm-yyyy
    case "nldate":
      return "^[0-3]?[0-9][-][01]?[0-9][-][12][0-9]{3}$";
      break;
    //yyyy-mm-dd
    case "date":
      return "^[12][0-9]{3}[-][01]?[0-9]-[0-3]?[0-9]$";
      break;
    case "integer":
      return "^[-]?[0-9]+$";
      break;
    case "posinteger":
      return "^[0-9]+$";
      break;
    case "float":
      return "^[+-]?[0-9]+([.][0-9]+)?$";
      break;
    case "nlfloat":
      return "^[+-]?[0-9]+([,][0-9]+)?$";
      break;
    case "url":
      return "^http[s]?://.{2,}";
      break;
    default:
      alert("Unknown validator added to a form element: '" + patternName+"'");
    }
}

function showFormMessage(formID,msg) {
	if (msg!="") {
		$("#"+formID+"Message").html(msg);
		$("#"+formID+"Message").show();
	} else {
		$("#"+formID+"Message").hide();
	}
}

function hideFormMessage(formID) {
	$("#"+formID+"Message").hide();
}

function removeValidationError(fieldName) {
	$("#xsforms_errormsg_"+fieldName).hide();
}

function setValidationError(fieldName,validator) {
	$("#xsforms_errormsg_"+fieldName).show();
}

function isValidEmail(email) {
	var emailValidator="^[0-9a-zA-Z][-_0-9a-zA-Z.]*@[-_0-9a-zA-Z.]+[.][a-zA-Z]+$";
	return validateValue(email,emailValidator);
}

function isValidImage(ext) {
	return (ext && /^(jpg|jpeg|png|gif)$/i.test(ext));
}

/**
 * Init
 */
function initItemsContainer(loaderPath,container) {
	if (!container) {
		$container = $('#flowcontainer');
	} else {
		$container = container;
	}

	$container.imagesLoaded(function(){
		$container.isotope({
			itemSelector : '.blink'
		});
	});

	$container.infinitescroll({
			navSelector  : '#load',    				// selector for the paged navigation
			nextSelector : '#nextItemsLink',  // selector for the NEXT link (to page 2)
			itemSelector : '.blink',   				// selector for all items you'll retrieve
			loading: {
					finishedMsg: 'No more items.',
					img: '/images/infscroll_loader.gif',
					msgText: 'Loading...'
			},
			pathParse:[loaderPath,''],
			debug: false
		},
		function(newElements) {
		  var $newElems = $(newElements);
		  $newElems.imagesLoaded(function(){
		    $container.isotope('appended', $newElems );
		  });
		}
	);
}

/**
 * Focus / exit invoervelden
 */
function focusBox(b,val) {
  if (b.value==val) {
    b.style.color='#333';
    b.value='';
  }
}

function exitBox(b,val) {
  if (b.value=='') {
    b.style.color='#bbb';
    b.value=val;
  }
}

function focusUrlBox(b) {
	b.style.color='#555';
}

function exitUrlBox(b,val) {
	if (b.value=='http://') {
		b.style.color='#bbb';
	} else {
		b.style.color='#555';
	}
}


/*
function resetBox(b,val) {
  if ($('#zoekBox').value==zoeken) {
    $('#zoekBox').value="";
  }
}
*/

function focusMessageBox(txt) {
	ta=$('.message-box');
	if (ta.val()==txt) {
		ta.val('');
	}
}

function blurMessageBox(txt) {
	ta=$('.message-box');
	if (ta.val()=='') {
		ta.val(txt);
	}
}

/**
 * Comments
 */
var $container;
var killCommentTimer;
var currBlinkID=0;

function showAddComment(blinkID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	clearTimeout(killCommentTimer);

	//staan we nog niet in comment mode, dan naar comment mode
	if ($('#blink_'+blinkID).data("comment")!=1) {
		$('#blink_'+blinkID).data("comment",1);

		var commentForm = '<div id="addComment'+blinkID+'" class="addcomment clearfix"><form id="saveCommentForm'+blinkID+'" name="saveCommentForm"><input type="hidden" name="cmd" value="addcomment"><input type="hidden" name="itemID" value="'+blinkID+'"><a href="#" class="thumb"><img src="'+avatar+'" width="30" height="30"></a><div class="info"><textarea name="comment" class="comment comment_flow"  onblur="blurComment(this,'+blinkID+')"></textarea></div></form></div>';

		$('#blink_'+blinkID).find('.reactions-container').append(commentForm);
		$('#blink_'+blinkID).find('.comment_flow').focus();
		$container.isotope('reLayout');
		initCommentFlowBox(blinkID);
	}

}

function initCommentFlowBox(blinkID) {
	$('body').delegate('.comment_flow', 'keyup', function(event) {
		if (event.keyCode == 13 && event.shiftKey) {
		event.stopPropagation();
		} else if(event.keyCode == 13) {
			if ($(this).val().length < 2) {
				$(this).val('');
			} else {
				saveComment(blinkID);
			}
		} else if(event.keyCode == 27) {
			$(this).val('');
		}
	});
}



/**
 * Comments
 */

function makeExpandingArea(container) {
 var area = container.querySelector('textarea');
 var span = container.querySelector('span');

 if (area.addEventListener) {
   area.addEventListener('input', function() {
     span.textContent = area.value;
   }, false);
   span.textContent = area.value;
 } else if (area.attachEvent) {
   // IE8 compatibility
   area.attachEvent('onpropertychange', function() {
     span.innerText = area.value;
   });
   span.innerText = area.value;
 }
 // Enable extra CSS
 container.className += ' active';
}


function initCommentWhiteBoxes() {
	$('body').delegate('.comment-box', 'keyup', function(event) {
		if (event.keyCode == 13 && event.shiftKey) {
		event.stopPropagation();
		} else if(event.keyCode == 13) {
			if ($(this).val().length < 2) {
				clearCommentBox();
			} else {
				saveCommentWhiteBox('<xsfield src="ID"></xsfield>');
				$('#add-comment-whitebox').fadeTo(100, 0.2);
				clearCommentBox();
			}
		} else if(event.keyCode == 27) {
			$(this).val('');
		}
	});
}

function initMessageBox() {
	$('body').delegate('.message-box', 'keyup', function(event) {
		if (event.keyCode == 13 && event.shiftKey) {
		event.stopPropagation();
		} else if(event.keyCode == 13) {
			if ($(this).val().length < 2) {
				$(this).val('');
			} else {
				sendMessage();
				$(this).val('');
			}
		} else if(event.keyCode == 27) {
			$(this).val('');
		}
	});
}

function clearCommentBox() {
	$('.expandingArea span').empty();
	$('.comment-box').val('');
}

/**
 * Triggered when comment-textare loses focus
 */
function blurComment(ta,blinkId) {
	if (!ta.value) {
		killCommentTimer=setTimeout('removeComment('+blinkId+')',500);
	}
}

/**
 * Save a comment to the server
 */
function saveComment(blinkID) {
	$('#btnSaveComment'+blinkID).attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_comment.php",
	  dataType: "json",
	  data: $('#saveCommentForm'+blinkID).serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#addComment'+blinkID).after(result.comment)
	  		$('#addComment'+blinkID).remove();
	  		$('#blink_'+blinkID).removeData("comment");
	  		$container.isotope('reLayout');
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#btnSaveComment'+blinkID).removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error saving your comment. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#btnSaveComment').removeAttr("disabled");
	  }
	});
}

function addLike(itemID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_comment.php",
	  dataType: "json",
	  data: "cmd=add_like&itemID="+itemID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#blink_'+itemID+' .flow-social-container div.like').html(result.likes+' likes');
	  		$container.isotope('reLayout');
	  	} else {
	  		/*
	  		if (result.error) {
	  			$('.i-like a').prepend('<div id="like-error">You already like this</div>');
	  			$('#like-error').delay(2000).fadeOut(100);
	  		}
	  		*/
	  		alert("You already like this item!");
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error processing your request. We apologise for the inconvenience.\n\nResponse from the server is:\n\n"+xhr.responseText);
	  }
	});
}

function deleteComment(commentID) {
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_comment.php",
	  dataType: "json",
	  data: "cmd=delete_comment&commentID="+commentID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#comment'+commentID).remove();
	  		$container.isotope('reLayout');
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("Unable to remove your comment. We apologise for the inconvenience.\n\nResponse from the server is:\n\n"+xhr.responseText);
	  }
	});
}

function reportItem(currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$.ajax({
	  type: "POST",
	  url: "/scripts/report_item.php",
	  dataType: "json",
	  data: $('#report-item').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#reportThisBlink').replaceWith("Blink reported as inappropriate.");
	  		removeReportAlert();
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error processing your request. We apologise for the inconvenience.\n\nResponse from the server is:\n\n"+xhr.responseText);
	  }
	});
}

/**
 * Removes the empty comment container
 */
function removeComment(blinkId) {
	$('#blink_'+blinkId).find('.addcomment').remove();
	$container.isotope('reLayout');
	$('#blink_'+blinkId).data("comment",0);
}

/* ############################# WHITE BOX ############################# */

/**
 * Show item in a whitebox
 */
function loadItem(blinkID) {
	location.hash = '#'+blinkID;

	if (currBlinkID==0) {
		$('body').addClass('noflow');

		if ($container) {
			if ($container.infinitescroll) {
				$container.infinitescroll('pause');
			}
		}
		
		$('body').prepend('<div class="overlaybg"></div><div class="overlay"><div class="whitebox"></div></div>');
	}
	$('.whitebox').load('/scripts/item.php?id='+blinkID);

	currBlinkID=blinkID;
}

function addBlink(currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	if (currBlinkID==0) {
		$('body').addClass('noflow');

		if ($container) {
			if ($container.infinitescroll) {
				$container.infinitescroll('pause');
			}
		}
		$('body').prepend('<div class="overlaybg"></div><div class="overlay"><div class="reblinkbox"></div></div>');
		$('.reblinkbox').load('/blink_it/add_blink', function() {
			$('#addblink-url').focusEnd();
		});
	}
}

function addImage(currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	if (currBlinkID==0) {
		$('body').addClass('noflow');

		if ($container) {
			if ($container.infinitescroll) {
				$container.infinitescroll('pause');
			}
		}
		$('body').prepend('<div class="overlaybg"></div><div class="overlay"><div class="reblinkbox"></div></div>');
		$('.reblinkbox').load('/blink_it/add_image', function() {
			$('#addblink-url').focusEnd();
			avatarUploader=initPictureUploader();
		});
	}
}

function editItem(itemID) {
	if (currBlinkID==0) {
		$('body').addClass('noflow');

		if ($container) {
			if ($container.infinitescroll) {
				$container.infinitescroll('pause');
			}
		}
		$('body').prepend('<div class="overlaybg"></div><div class="overlay"><div class="reblinkbox"></div></div>');
		$('.reblinkbox').load('/blink_it/blink_edit?id='+itemID, function() {
			//$('#addblink-url').focusEnd();
		});
	}
}

function showAddBlinkSubmit() {
	$('#addBlink_input-url, #addBlink_get-images').hide();
	$('#addBlink_submit-blink').show();
}

function prepareAddBLinkSubmit(imageSrc,blinkDescription) {
	imageSrc=unescape(imageSrc);
	blinkDescription=unescape(blinkDescription);
	im.src=imageSrc;
	$('#blinkItImage').val(imageSrc);
	$('#blinkItUrl').val($('#addblink-url').val());
	if (blinkDescription) {
		$('#description').val(blinkDescription);
		$('.description-label').hide();
	}
	showAddBlinkSubmit();
}

function getImagesFromUrl() {

	$('#addBlink_get-images').empty();
	var imagesFound=false;
	var targetWidth=180;
	var targetHeight=160;

	$.ajax({
	  type: "GET",
	  url: "/scripts/get_images_from_url.php",
	  dataType: "json",
	  data: $('#addBlink').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
				for (var i=0;i < result.images.length;i++) {
					var srcImg=result.images[i];
					if (srcImg.src) {
						var im=document.createElement('img');
						im.alt=srcImg.alt;
						im.onload=function() {
							var imageWidth=this.width;
							var imageHeight=this.height;

							if (imageWidth >= minwidth && imageHeight >= minheight) {

								if (!imagesFound) {
									$('#addBlink_get-images').innerHTML='';
									imagesFound=true;
								}

								var factor=calcRescaleFactor(imageWidth,imageHeight,targetWidth,targetHeight);
								if (factor>1) {
									var scaledW = imageWidth / factor;
									var scaledH = imageHeight / factor;
								} else {
									var scaledW = imageWidth;
									var scaledH = imageHeight;
								}

								this.style.width=scaledW+'px';
								this.style.height=scaledH+'px';
								this.style.paddingTop=((targetHeight - scaledH) / 2)+'px';
								this.style.paddingLeft=((targetWidth - scaledW) / 2)+'px';

								//image
								var imageContainer=document.createElement('div');
								imageContainer.setAttribute("class","image-container");

								//dimensions label
								var sizeContainer=document.createElement('div');
								sizeContainer.setAttribute("class","size-container");
								sizeContainer.style.width=imageContainer.style.width;
								sizeContainer.innerHTML=getBlinkQualityDescriptionByWidth(imageWidth);
								//sizeContainer.innerHTML=imageWidth + " x " + imageHeight + " pixels";
								sizeContainer.style.zIndex=2147483647;

								var blinkHandler=document.createElement('div');
								var blinkDescription=this.alt;

								blinkHandler.setAttribute("class","blink-handler");
								blinkHandler.innerHTML="<a href=\"javascript:;\" onclick=\"prepareAddBLinkSubmit('"+escape(this.src)+"','"+escape(this.alt)+"');\">Blink-it</a>";

								imageContainer.appendChild(this);
								imageContainer.appendChild(sizeContainer);
								imageContainer.appendChild(blinkHandler);

								$('#addBlink_get-images').append(imageContainer);
							}
						}
						im.src=srcImg.src;
					}
				}
	  		$('#addBlink_get-images').show();
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	 	},
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error saving your comment. We apologise for the inconvenience.\n\n"+xhr.responseText);
	  }
	});
}

/**
 * Returns textual quality descriptoin based on image width
 */
function getBlinkQualityDescriptionByWidth(imageWidth) {
	if (imageWidth >= 765) {
		return "Very good quality";
	} else if (imageWidth >= 400) {
		return "Okay quality";
	} else if (imageWidth >= 100) {
		return "Poor quality";
	}
	return "";
}

function getImagesFromUpload() {
	alert('upload image');
}

function reblink(blinkID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	if (currBlinkID==0) {
		$('body').addClass('noflow');

		if ($container.infinitescroll) {
			$container.infinitescroll('pause');
		}
		$('body').prepend('<div class="overlaybg"></div><div class="overlay"><div class="reblinkbox"></div></div>');
		$('.reblinkbox').load('/reblink/'+blinkID, function() {
			initBlinkItPage();
		});

	} else {
		//We hebben al een whitebox
		$('#mainframe').css({'visibility':'hidden', 'width':'615px'}).load('/reblink/'+blinkID, function() {
		  $('.whitebox').switchClass('whitebox','reblinkbox',350);
		  $('#mainframe').css("visibility","visible");
		  initBlinkItPage();
		});
	}
}

function closeReblinkBox() {
	$('.overlaybg, .overlay, .reblinkbox').remove();
	$('body').removeClass('noflow');
	currBlinkID=0;

	if ($container.infinitescroll) {
		$container.infinitescroll('resume');
	}
}

/**
 * Show 'add comment' form in white box
 */
function addComment(currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$('.comment-box').focus();
}

function saveCommentWhiteBox(blinkID) {
	$('#btnSaveComment').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_comment.php",
	  dataType: "json",
	  data: $('#saveCommentForm').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		//Maak comment box leeg
	  		$('.comment-box').val('');
	  		$('#add-comment-whitebox').fadeTo(100, 1);
	  		$('#add-comment-whitebox').before(result.comment);

	  		//Voeg comment toe in de mother page
	  		//$('#addComment'+blinkID).after(result.comment)
	  		//$container.isotope('reLayout');
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#btnSaveComment').removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error saving your comment. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#btnSaveComment').removeAttr("disabled");
	  }
	});
}

function addLikeWhiteBox(itemID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_comment.php",
	  dataType: "json",
	  data: "cmd=add_like&itemID="+itemID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#likes-container').show();
	  		$('#likes-container').find('td.right').prepend($('#avatar-template').html());

	  		//Update motherpage
	  		$('#blink_'+itemID+' .flow-social-container div.like').html(result.likes+' likes');
	  		$container.isotope('reLayout');
	  	} else {
	  		alert("You already like this!");
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error processing your request. We apologise for the inconvenience.\n\nResponse from the server is:\n\n"+xhr.responseText);
	  }
	});
}

function sendMessage() {
	$('#send-message-button').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/messaging.php",
	  dataType: "json",
	  data: $('#sendMessageForm').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#messaging-message-sent').show();
	  		$('#send-message-text').val('');
	  	} else {
	  		alert("Unable to send your message.");
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("There was an error processing your request. We apologise for the inconvenience.\n\nResponse from the server is:\n\n"+xhr.responseText);
	  }
	});
	$('#send-message-button').removeAttr("disabled");
}

/*
function previousBlinkWhiteBox() {
	var previousBlinkID=$('#blink_'+currBlinkID).prevAll('.blink:first').attr("id");
	if (previousBlinkID !== undefined) {
		previousBlinkID=previousBlinkID.substr(6);
		if (!isNaN(previousBlinkID)) {
			loadItem(previousBlinkID);
		}
	}
}

function nextBlinkWhiteBox() {
	var nextBlinkID=$('#blink_'+currBlinkID).nextAll('.blink:first').attr("id");
	if (nextBlinkID !== undefined) {
		nextBlinkID=nextBlinkID.substr(6);
		if (!isNaN(nextBlinkID)) {
			loadItem(nextBlinkID);
		}
	}
}
*/

function previousBlinkInViewWhiteBox(itemIdsInView) {
	n=itemIdsInView.length;
	for (var i=0;i<n;i++) {
		if (itemIdsInView[i]==currBlinkID) {
			if (i > 0) {
				var previousBlinkID=itemIdsInView[i-1];
			} else {
				var previousBlinkID=itemIdsInView[n-1];
			}

			loadItem(previousBlinkID);
			return;
		}
	}
}

function nextBlinkInViewWhiteBox(itemIdsInView) {
	n=itemIdsInView.length;
	for (var i=0;i<n;i++) {
		if (itemIdsInView[i]==currBlinkID) {
			if (i < n-1) {
				var nextBlinkID=itemIdsInView[i+1];
			} else {
				var nextBlinkID=itemIdsInView[0];
			}
			loadItem(nextBlinkID);
			return;
		}
	}
}

//#######################################################
//### FOLLOW / UNFOLLOW
//#######################################################
function followView(viewID,viewOwnerID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$('#followView').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_follow.php",
	  dataType: "json",
	  data: "cmd=follow&view="+viewID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#followView'+viewID).hide();
	  		$('#unfollowView'+viewID).show();

	  		$('#followUser'+viewOwnerID).hide();
	  		$('#followingUser'+viewOwnerID).show();
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#followView').removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("We were unable to process your request. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#followView').removeAttr("disabled");
	  }
	});
}

function unfollowView(viewID,viewOwnerID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$('#unfollowView').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_follow.php",
	  dataType: "json",
	  data: "cmd=unfollow&view="+viewID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#unfollowView'+viewID).hide();
	  		$('#followView'+viewID).show();

				//check of de huidige gebruiker nog views van deze gebruiker volgt. Pas hierop knoppen in de linkerkolom aan
	  		if (result.followCount==0) {
		  		$('#followUser'+viewOwnerID).show();
		  		$('#followingUser'+viewOwnerID).hide();
		  	}

	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#unfollowView').removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("We were unable to process your request. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#unfollowView').removeAttr("disabled");
	  }
	});
}

function followUser(userID) {
	$('followUser'+userID).attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_follow.php",
	  dataType: "json",
	  data: "cmd=follow_user&user="+userID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#followingUser'+userID).show();
	  		$('#followUser'+userID).hide();

	  		$('.follow-view-button').hide();
	  		$('.unfollow-view-button').show();
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#followUser'+userID).removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("We were unable to process your request. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#followUser'+userID).removeAttr("disabled");
	  }
	});
}

function unfollowUser(userID,currUserID) {
	if (currUserID==0) {
		document.location.href="/login";
		return;
	}

	$('#followingUser'+userID).attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_follow.php",
	  dataType: "json",
	  data: "cmd=unfollowuser&user="+userID,
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#followingUser'+userID).hide();
	  		$('#followUser'+userID).show();

	  		$('.follow-view-button').show();
	  		$('.unfollow-view-button').hide();
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#followingUser'+userID).removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("We were unable to process your request. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#followingUser'+userID).removeAttr("disabled");
	  }
	});
}

function saveViewsOrder() {
	var items=$('.view-overview').map(function(){
     return $(this).get(0).id.replace(/view/,"");
  }).get().join(",");

	$.post("/scripts/edit_view.php", { cmd: "change_order", items: items } );
}

//#######################################################
//### BLINK-IT AND REBLINK-IT
//#######################################################

//Init BlinkIt and ReblinkIt page elements
function initBlinkItPage() {

	$('#selected-view').click(function() {
		$('#options').show();
		$('#input-description, #description').hide();
	});

	if ($('#description').val() == '') {
		$('#description').next('.description-label').show();
	} else {
		$('#description').next('.description-label').hide();
	}

	$('#description').focus(function() {
		if ( $(this).val() == '') {
			$(this).next('.description-label').hide();
		}
	});

	$('#description').blur(function() {
		if ( $(this).val() == '' ) {
			$(this).next('.description-label').show();
		}
	});

}

//Select a view from the views list
function selectView(title,viewID) {
	$('#selected-view').html(title);
	$('#selectedViewID').val(viewID);
	$('#options').hide();
	$('#input-description, #description').show();
}

//Step 2 in create new view process
function selectViewCategory() {
	if ($('#new-view-title').val()) {
		$('#selected-view').html($('#new-view-title').val());
		$('#options').hide();
		$('#select-category').show();
	} else {
		$('#new-view-title').focus();
	}
}

//Creates a new view on the server
function addView(title,category) {
	$('#new-view-title-copy').val($('#new-view-title').val());
	$('#new-view-category').val(category);
	$('#select-category').hide();
	$('#add-view').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/edit_view.php",
	  dataType: "json",
	  data: $('#formNewView').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#options ul').append('<li onclick="selectView($(this).html(),'+result.viewID+')">' + $('#new-view-title').val() + '</li>');
	  		selectView(title,result.viewID)
	  	} else {
	  		if (result.error) {
	  			alert(result.error);
	  		}
	  	}
	  	$('#add-view').removeAttr("disabled");
	  },
		error: function (xhr, desc, exceptionobj) {
			alert("We were unable to add your new view. We apologise for the inconvenience.\n\n"+xhr.responseText);
			$('#add-view').removeAttr("disabled");
	  }
	});
}

function calcRescaleFactor(w,h,targetWidth,targetHeight) {
	if (targetWidth==0 && targetHeight==0) {
		//geen scaling
		return 1;
	} else if (targetWidth==0) {
		//scale naar hoogte
		return h / targetHeight;
	} else if (targetHeight==0) {
		//scale naar breedte
		return w / targetWidth;
	} else {
		//scale naar beide
		var fact_w = w / targetWidth;
		var fact_h = h / targetHeight;
		if(fact_w < fact_h) {
			return fact_h;
		}	else {
			return fact_w;
		}
	}
}


/**
 * Twitter connect checkbox (blink it /add blink)
 */
function checkConnectedToTwitter(chk) {
	if (chk.checked) {
		if (!connectedToTwitter) {
			showConnectToTwitterDialog();
		}
	} else {
		hideConnectToTwitterDialog();
	}
}

function hideConnectToTwitterDialog() {
	$('#connectToTwitterDialog').hide();
}

function showConnectToTwitterDialog() {
	$('#connectToTwitterDialog').show();
}

function setSuccesfullyConnectedToTwitter() {
	connectedToTwitter=true;
	$('#connectToTwitterDialog').hide();
	//$('#succesfullyConnectedToTwitterDialog').show();
}

/**
 * Facebook connect checkbox (blink it /add blink)
 */
function checkConnectedToFacebook(chk) {
	if (chk.checked) {
		if (!connectedToFacebook) {
			showConnectToFacebookDialog();
		}
	} else {
		hideConnectToFacebookDialog();
	}
}

function hideConnectToFacebookDialog() {
	$('#connectToFacebookDialog').hide();
}

function showConnectToFacebookDialog() {
	$('#connectToFacebookDialog').show();
}

function setSuccesfullyConnectedToFacebook() {
	connectedToFacebook=true;
	$('#connectToFacebookDialog').hide();
	//$('#succesfullyConnectedToFacebookDialog').show();
}


//#######################################################
//### ERRORPAGINA (feedback via boxje)
//#######################################################
function saveErrorComment() {
	$('#btnSaveComment').attr("disabled","disabled");
	$.ajax({
	  type: "POST",
	  url: "/scripts/errorpage_comment.php",
	  dataType: "json",
	  data: $('#leave-comment').serialize(),
	  success: function(result) {
	  	if (result.status=="OK") {
	  		$('#feedbackReceived').show();
	  	} else {
	  		$('#btnSaveComment').removeAttr("disabled");
	  		alert("We were unable to save your comment. You can send us an email at: info@20blinks.com.");
	  	}
	  },
		error: function (xhr, desc, exceptionobj) {
			$('#btnSaveComment').removeAttr("disabled");
  		alert("We were unable to save your comment. You can send us an email at: info@20blinks.com..\n\n"+xhr.responseText);
	  }
	});
}

//#######################################################
//### DEBUGGERS
//#######################################################
function debugObj(obj) {
	attrs="";
	vals="";
	for( var attr in obj ) {
		if (attrs) { attrs+=", "; }
		attrs+=attr;
		if (typeof obj[attr] == "object") {
			var nestedAttrs="";
			for(var attr2 in obj[attr] ) {
				if (nestedAttrs) { nestedAttrs+=", "; }
				nestedAttrs+=attr2;
			}
			vals+='\n'+attr+': {'+nestedAttrs+'}';
		} else {
			vals+='\n'+attr+': '+obj[attr];
		}
	}

	return attrs + "\n----------------------------------------------------------------\n"+vals;
}

function debug(obj) {
	var s=debugObj(obj);
	alert(s);
}
