/* Init console for browsers without it */

if (!console) {
	var console = {
		'log' : function(v) {
			return false;
		},
		'debug' : function(v) {
			return false;
		}
	};
}

/* Non conflicting JQuery */
var $j = jQuery.noConflict();

var carousel = {
	'opts' : {
		ImageFlowID : 'min-e-art',
		aspectRatio : 480 / 320, /*
									 * Aspect ratio of the ImageFlow container
									 * (width divided by height)
									 */
		buttons : false, /* Toggle navigation buttons */
		captions : true, /* Toggle captions */
		imageCursor : 'default', /*
									 * Cursor type for all images - default is
									 * 'default'
									 */
		imageFocusM : 1 + 330 / 200, /*
										 * Multiplicator for the focussed image
										 * size in percent
										 */
		imageFocusMax : 4, /*
							 * Max number of images on each side of the focussed
							 * one
							 */
		imageScaling : true, /* Toggle image scaling */
		imagesHeight : 260 / 320, /*
									 * Height of the images div container in
									 * percent
									 */
		imagesM : 1.0, /* Multiplicator for all images in percent */
		onClick : function() {
			return false;
		}, /* Onclick behaviour */
		opacity : false, /* Toggle image opacity */
		opacityArray : [ 10, 8, 6, 4, 2 ], /*
											 * Image opacity (range: 0 to 10)
											 * first value is for the focussed
											 * image
											 */
		percentLandscape : 100, /* Scale landscape format */
		percentOther : 100, /* Scale portrait and square format */
		preloadImages : true, /*
								 * Toggles loading bar (false: requires img
								 * attributes height and width)
								 */
		reflections : false, /* Toggle reflections */

		scrollbarP : 0.95, /* Width of the scrollbar in percent */
		slider : true, /* Toggle slider */
		sliderCursor : 'e-resize', /* Slider cursor type - default is 'default' */
		sliderWidth : 14, /* Width of the slider in px */
		startID : 1, /* Glide to this image ID on startup */
		startAnimation : false, /*
								 * Animate images moving in from the right on
								 * startup
								 */
		xStep : 240, /* Step width on the x-axis in px */
		onChange : function() {
			short.reset();
		}

	},
	'category' : 0,
	'estamp' : null,
	'imgflow' : new ImageFlow(),
	'getSelected' : function() {
		if (carousel.imgflow.image) {
			carousel.estamp = carousel.imgflow.image.getAttribute('id');
		} else {
			carousel.estamp = null;
		}
		return carousel.estamp;
	},

	'is_loading' : false,
	'load' : function(cat) {
		carousel.category = cat;
		if (carousel.is_loading)
			return false;
		var opts = {
			'sort' : 'timechanged',
			'dir' : 'DESC',
			'short' : 1,
      'search[paid]': false
		};
		if (carousel.category)
			opts['search[category.id]'] = carousel.category;
		var url = '/api.php/estamps';
		carousel.is_loading = true;
		$j.getJSON(url, opts, function(data) {
			if (data.success) {
				$j("#min-e-art").html('');
				for (i = 0; i < data.data.length; i++) {
					var img = data.data[i];
					// console.log(img);
				var txt = '<a href='
				' onclick="show_details(\'' + img.id + '\');return false">'
						+ img.name + '</a> ' + img.author
						+ (img.intro ? '<br />' + img.intro : '');
				$j("#min-e-art")
						.append(
								"<img width='320' height='260' src='/api.php/"
										+ img.id + "?image' id='" + img.id
										+ "' alt='" + escape(img.name) + "'"
										+ "author='" + escape(img.author) + "'"
										+ "intro ='"
										+ (img.intro ? escape(img.intro) : '')
										+ "' />");
			}
			carousel.imgflow.init(carousel.opts);
			carousel.is_loading = false;
		}
	}	);
	}
};

var buildCategorySelect = function() {
	var opts = {
		'short' : '1',
		'sort' : 'name',
		'dir' : 'ASC'
	};
	 opts['search[paid]'] = false;
	// opts['search[categories.active]'] = true;
	$j.getJSON('/api.php/categories', opts, function(cat) {
		$j("#selectoptions").html(
				'<div class="selectitems"><span>All types</span></div>');
		$j(cat.data).each(function(ix, i) {
			// console.log(ix, i);
				$j("#selectoptions").append(
						"<div id=\"" + i.id + "\" class=\"selectitems\"><span>"
								+ i.name + " (" + i.count + ")</span></div>");
			});
		$j("#iconselectholder").append($j("#selectoptions")[0]);

	});
	carousel.load(0);
};
var defaults = {
	'destination_message' : '',
	'name_message' : '',
	'url_message' : '',
	'copy_btn' : '',
	'wait_img' : "<img src='/img/ajax_small.gif' />",

	'init' : function() {
		defaults.destination_message = $j('#destination_message').html();
		defaults.name_message = $j('#name_message').html();
		defaults.url_message = $j('#url_message').html();
		defaults.copy_btn = $j('#copy_btn').html();
	}
};

function Destination() {
	var this_dest = this;
	this.url = 'http://';
	this.isValid = false;
	this.processing = false;
	this.message = '';

	this.cached = [ {
		'url' : '',
		'isValid' : false,
		'message' : 'Please provide the destination URL'
	}, {
		'url' : 'http://',
		'isValid' : false,
		'message' : 'Please provide the destination URL'
	} ];

	this.reset = function() {
		if (this_dest.processing) {
			window.setTimeout(this_dest.reset, 200);
			return false;
		}
		this_dest.url = 'http://';
		this_dest.isValid = false;
		this_dest.message = defaults.destination_message;
		$j("#destination").val(this_dest.url);
		$j("#destination_message").html(this_dest.message);
		$j('#url').val('http://prsn.nl/');
		return false;
	};

	this.isCached = function(url) {
		var found = $j.grep(this_dest.cached, function(c) {
			try {
				return (c.url.toLowerCase() == url.toLowerCase());
			}
			catch(e){
				return false;
			}
		});
		if (found.length) {
			found = found[0];
			this_dest.url = found.url;
			this_dest.isValid = found.isValid;
			this_dest.message = found.message;
			this_dest.processing = false;
			return true;
		}
		return false;
	};
	this.addToCache = function() {
		this_dest.cached.push( {
			'url' : this_dest.url,
			'isValid' : this_dest.isValid,
			'message' : this_dest.message
		});
	};

	this.retries = 5; // five retires

	this.check = function() {
		var url = $j("#destination").val();
		var api = '/api.php/urls';
		var ok = true;
		this_dest.isValid = false;
		this_dest.url = url;
		this_dest.message = 'Checking destination';

		ok = !this_dest.isCached(url);

		if (ok && this_dest.processing) {
			if (this_dest.retries--) {
				window.setTimeout(this_dest.check, 200);
				return false;
			} else {
				this_dest.message = "Destination URL check timed out. Please try again";
				ok = false;
			}
		}
		$j("#destination_message").html(this_dest.message);
		if (!ok) {
			this_dest.processing = false;
			return false;
		}
		this_dest.processing = true;
		this_dest.retries = 5;

		$j.getJSON(api, {
			'destination' : this_dest.url
		}, function(data, text) {
			this_dest.isValid = data.success;
			if (data.message) {
				this_dest.message = data.message.replace(/\n/g, '<br />');
				this_dest.url = data.data.destination;
			} else
				this_dest.message = '';
			this_dest.addToCache();
			$j("#destination_message").html(this_dest.message);
			this_dest.processing = false;
		});
		return false;
	};
}

function Name() {
	var this_name = this;
	this.name = '';
	this.isValid = false;
	this.message = '';
	this.processing = false;
	this.cached = [];

	this.reset = function() {
		if (this_name.processing) {
			window.setTimeout(this_name.reset, 200);
			return false;
		}
		this_name.name = '';
		this_name.isValid = false;
		this_name.message = defaults.name_message;
		$j("#name").val(this_name.name);
		$j("#name_message").html(this_name.message);
		$j('#url').val('http://prsn.nl/');
		$j('#url').attr('disabled', 'disabled');

		return false;
	};
	this.isCached = function(name) {
		var found = $j.inArray(name, this_name.cached);
		if (found != -1) {
			this_name.name = name;
			this_name.isValid = false;
			this_name.message = 'This keyword is already used';

			return true;
		}
		return false;
	};

	this.addToCache = function() {
		if (-1 == $j.inArray(this_name.name, this_name.cached))
			this_name.cached.push(this_name.name);
		this_name.message = 'This keyword is already used';
	};
	this.retries = 5;
	this.check = function() {

		var name = $j("#name").val();
		var api = '/api.php/urls';
		var ok = true;

		this_name.isValid = false;
		this_name.name = name;
		this_name.message = 'Checking name';

		if (name == '') {
			this_name.isValid = true;
			this_name.message = 'Auto keyword';
			$j('#url').removeAttr('disabled');
			$j("#url").focus();
			ok = false;
		}
		if (ok && !name.match(/^[a-z0-9_]{1,15}$/i)) {
			this_name.message = '"' + name + '" is not a valid keyword';
			ok = false;
		}

		ok = ok && !this_name.isCached(name);

		if (ok && this_name.processing) {
			if (this_name.retries--) {
				window.setTimeout(this_name.check, 200);
				return false;
			} else {
				this_name.message = "Keyword check timed out. Please try again";
				ok = false;
			}
		}

		$j("#name_message").html(this_name.message);
		if (!ok) {
			this_name.processing = false;
			return false;
		}

		this_name.processing = true;
		this_name.retries = 5;

		$j.getJSON(api, {
			'name' : this_name.name
		}, function(data, text) {
			if (data.success) {
				this_name.isValid = true;
				this_name.message = 'OK';
				$j('#url').removeAttr('disabled');
			} else {
				this_name.name = data.data.name;
				this_name.isValid = false;
				this_name.addToCache();
				if (data.message)
					this_name.message = data.message.replace(/\n/g, '<br />');
				else
					this_name.message = '';
			}

			$j("#name_message").html(this_name.message);
			this_name.processing = false;
			if (this_name.isValid)
				$j("#url").focus();
		});
		return false;
	};
}

function ShortUrl() {
	var this_url = this;
	this.short = 'http://prsn.nl/';
	this.name = new Name();
	this.destination = new Destination();
	this.message = '';
	this.processing = false;
	this.reset = function() {
		this_url.name.reset();
		this_url.destination.reset();
		this_url.message = '';
		this_url.short = 'http://prsn.nl/';
		$j('#url_message').html(defaults.url_message);
		$j('#url').val(this_url.short);
		$j('#copy_btn').html(defaults.copy_btn);
		$j("#copy_btn").addClass('disabled');
		$j("#copy_btn").attr('disabled', 'disabled');
		return false;
	};

	this.create = function() {
		if ($j("#url").val() != "http://prsn.nl/")
			return false;
		console.log('create');
		var ok = true;
		var url = "/api.php/urls";
		var opts = {
			'estamp' : carousel.getSelected(),
			'user' : 1,
			'destination' : this_url.destination.url,
			'name' : this_url.name.name
		};
		$j('#url').val('http://prsn.nl/');
		$j('#copy_btn').html(defaults.wait_img);
		$j('#url_message').html('Processing');
		while (this_url.name.processing || this_url.destination.processing) {
			if (!this_url.processing) {
				window.setTimeout(this_url.create, 500);
			}
			return false;
		}

		if (!this_url.destination.isValid) {
			$j("#destination").select();
			$j('#copy_btn').html(defaults.copy_btn);
			$j('#url_message').html('Please provide a valid destination URL');
			return false;
		}
		if (!this_url.name.isValid) {
			$j("#name").select();
			$j('#copy_btn').html(defaults.copy_btn);
			$j('#url_message').html('Please provide a valid keyword');
			return false;
		}

		if (this_url.processing) {
			return false;
		}

		this_url.processing = true;
		$j
				.post(
						url,
						opts,
						function(data, text) {
							console.log(data);
							this_url.message = '';
							if (data.success) {
								this_url.short = 'http://prsn.nl/' + data.data.name;
								this_url.message = 'This is your shortened URL';
								this_url.name.name = data.data.name;
								$j('#copy_btn').html(defaults.copy_btn);
								$j("#copy_btn").removeClass('disabled');
								$j("#copy_btn").removeAttr('disabled');
								$j("#copy_btn").focus();
							} else {
								this_url.short = 'http://prsn.nl/';
								$j('#copy_btn').html(defaults.copy_btn);
								$j("#copy_btn").addClass('disabled');
								$j("#copy_btn").attr('disabled', 'disabled');
								if (data.message) {
									this_url.message = data.message.replace(
											/\n/g, '<br />');
								} else {
									this_url.message = 'Failure by creating of the short URL, please try again';
								}
							}
							$j("#url").val(this_url.short);
							$j("#name").val(this_url.name.name);
							$j("#url_message").html(this_url.message);
							this_url.processing = false;
						}, 'json');
		return false;
	};

	this.copy = function() {
		// console.log(url);
		if (window.clipboardData) {
			window.clipboardData.setData('text', $j("#url").val());
			alert($j("#url").val() + ' is in your clipboard');
		} else if ($j.browser.msie) {
			var url = document.getElementById('url');
			url.focus();
			url.select();
			var range = url.createTextRange();
			range.execCommand('Copy');
			alert($j("#url").val() + ' is in your clipboard');
		} else {
			var url = $j("#url");
			url.removeAttr('disabled');
			alert("Your browser doesn't support automatic copy to the clipboard.\nPlease use Ctrl+C or the browser interface to copy the selected URL in your clipboard.");
			url.select();
		}
		return false;
	};

}

var show_details = function(id) {
	var url = '/api.php/' + id;
	$j.getJSON(url, {}, function(data) {
		var html = "<img src='/api.php/" + data.data.image + "' alt='"
				+ data.data.intro + "'  height='260' width='320'/>";

		$j('#details').html(data.data.name);
		$j('#author').html('by ' + data.data.author);
		$j('#intro').html(html);
		$j('#description').html(data.data.description);
		Cufon.refresh();

		$j('#selected').fadeIn(200);
		try {
			pageTracker._trackPageview('details for ' + data.data.name);
		} catch (e) {
		}
	});
	$j('#selection').fadeOut(300);
	$j('#info').fadeOut(300);
	return false;
};
var hide_details = function() {
	if (window.location.search) {
		window.loaction.search = '';
	} else {
		$j('#selected').fadeOut(200, function() {
			$j('#selection').fadeIn(200);
			$j('#details').html('');
			$j('#description').html('');
			buildCategorySelect();
		});

	}
};
var hide_info = function() {
	$j('#info').fadeOut(200, function() {
		$j('#selection').fadeIn(200);
		$j('#info_text').html('');
		buildCategorySelect();
	});
};
var show_page = function(url) {
	$j("#left_content").hide();
	$j("#left_content").load(url, null, function() {
		$j("#left_content").fadeIn(300);
		Cufon.refresh();
		try {
			pageTracker._trackPageview(url);
		} catch (e) {
		}
	});
	$j("a.menu").removeClass('selected');
	$j('a.menu[href=' + url + ']').addClass('selected');

	return false;
};
var show_info = function(url) {
	$j("#info_text").load(url, null, function() {
		Cufon.refresh();
		$j('#info').fadeIn(200);
		try {
			pageTracker._trackPageview(url);
		} catch (e) {
		}

	});
	$j('#selection').fadeOut(300);
	$j('#selected').fadeOut(300);
	return false;
};
// Init page on document load

var short = new ShortUrl();
$j(this).ready(
		function() {
			show_page('/home.html');
			$j('a.menu[href=index.html]').addClass('selected');
			buildCategorySelect();
			$j("#destination").val('http://');
			defaults.init();
			short.reset();

			$j("a.menu").live('click', function() {
				if ($j(this).attr('target'))
					return true;
				return show_page($j(this).attr('href'));
			});
			$j("a.info").live('click', function() {
				if ($(this).attr('target') == '_top')
					window.location = $j(this).attr('href');
				return show_info($j(this).attr('href'));
			});
			$j("a.estamp").live('click', function() {
				return show_details($j(this).attr('href'));
			});
			/*
			 * $j("#destination").focus(function(e){return
			 * short.destination.reset;}); $j("#name").focus( function(e){return
			 * short.name.reset;}); $j("#url").focus(function(e){return
			 * short.create;}); $j("#copy_btn").click( function(e){return
			 * short.copy;});
			 * 
			 * $j("#destination").blur(function(e){ short.destination.check;});
			 * $j("#name").blur(function(e){return short.name.check;});
			 */
			$j("#destination").keydown(function(e) {
				var code = e.keyCode || e.which;
				if (code == 13) {
					short.destination.check();
					return false;
				} else if (code == 27) {
					short.destination.reset();
					return false;
				}
			});
			$j("#name").keydown(function(e) {
				var code = e.keyCode || e.which;
				if (code == 13) {
					return short.name.check();
				} else if (code == 27) {
					return short.name.reset();
				}

			});

			$j("#iconselect").live('click', function() {
				$j("#iconselectholder").toggle("slow");
			});
			$j(".selectitems").live('moseover', function() {
				$j(this).addClass("hoverclass");
			});
			$j(".selectitems").live('mouseout', function() {
				$j(this).removeClass("hoverclass");
			});
			$j(".selectitems").live('click', function() {
				$j(".selectedclass").removeClass("selectedclass");
				$j(this).addClass("selectedclass");
				var thisselection = $j(this).html();
				$j("#iconselect").html(thisselection);
				$j("#iconselectholder").toggle("slow");
				carousel.load($j(this).attr('id'));
			});

			if (window.location.search) {
				var url = '/api.php/' + window.location.search.substring(1);
				$j.getJSON(url, {}, function(data) {
					if (data.data.estamp) {
						show_details(data.data.estamp.id);
					} else if (data.data.id
							&& data.data.id.substring(0, 7) == 'estamps') {
						show_details(data.data.id);
					} else {
						window.location = '/index.html';
					}
				});
			}

		});
