/*******************************************************************************

	CSS on Sails Framework
	Title: Monokle
	Author: XHTMLized (http://www.xhtmlized.com/)
	Date: January 2011

*******************************************************************************/

function onPage(page, fn) {
	if ($('body').hasClass(page)) fn.call();
}

Monokle = {
	customTextfields: function() {
		$('.textfield, .textarea').each(function() {
			var $div = $(this);
			var $input = $div.find('input, textarea');
			var $type = $div.hasClass('textfield') ? 'textfield' : 'textarea';

			function filledClass(div, input) {
				if (input.val() == "") {
					div.removeClass(sprintf('%s-filled', $type));
				} else {
					div.addClass(sprintf('%s-filled', $type));
				}
			}

			$input.bind({
				focus: function() {
					$div.addClass(sprintf('%s-active', $type));
				},
				blur: function() {
					$div.removeClass(sprintf('%s-active', $type));
					filledClass($div, $input);
				}
			});

			filledClass($div, $input);

			$div.parent().find(sprintf('label[for=%s]', $input.attr('id'))).prependTo($div).addClass('inside');
			$div.find('.wpcf7-not-valid-tip-no-ajax').insertAfter($div);
		});
	},
	replaceSubmits: function() {
		function replaceButton(button, link) {
			link.bind('click', function() {
				$(this).unbind('click', false);
				$(this).closest('form').submit();
			});

			link.insertBefore(button);
			button.hide();
		}

		$('form input:submit').each(function() {
			var $button = $(this);
			var $link = $('<a />', {
				'class': 'button',
				html: sprintf('<span>%s</span>', $button.val())
			});
			replaceButton($button, $link);
		});
	},
	createTopCarousel: function() {
		if ($('#carousel').length > 0) {
			var options = {
				itemList: $('#carousel-data ul.switcher'),
				titleElement: $('#carousel-data p.title'),
				moreLink: $('#carousel-data a.button'),
				linkImages: arguments[0]
			}

			if ($.browser.msie && $.browser.version == "6.0") {
				options.controlsElement = $('#carousel');
				options.inactiveOpacity = 0;
			}

			Monokle.carousel = $('#carousel').attach(Carousel, options).carousel_instance;
		}
	},
	createEntryCarousel: function() {
		if ($('#carousel').length > 0) {
			var options = {
				width: 602,
				adjustWrapper: false,
				itemList: $('#carousel-data ul.switcher')
			}

			if ($.browser.msie && $.browser.version == "6.0") {
				options.controlsElement = $('#carousel');
				options.inactiveOpacity = 0;
			}

			Monokle.carousel = $('#carousel').attach(Carousel, options).carousel_instance;
		}
	},
	embedProcessVideo: function() {
		var $el = $('a#process-video');
		$el.bind('click', function(e) {
			e.preventDefault();

			var video_id = $(this).data('vimeo_id');
			var $wrapper = $('<div />');

			var iframe_html = sprintf('<iframe src="http://player.vimeo.com/video/%s?portrait=0&autoplay=1&js_api=1&js_swf_id=vimeo_%s" width="%s" height="%s" frameborder="0" id="vimeo_%s"></iframe>', video_id, video_id, $(this).find('img').width(), $(this).find('img').height(), video_id);

			$wrapper.append(iframe_html);
			$(this).replaceWith($wrapper)

			var video_object = $wrapper.find('iframe')[0];
			Froogaloop.init([this.video_object]);
		});
	},
	embedProcessVideoa: function() {
		var $el = $('a#process-video');
		$el.bind('click', function(e) {
			var video_id = $el.data('vimeo_id');
			var swf_id = 'process-video';
			var flashvars = {
				clip_id: video_id,
				show_portrait: 0,
				show_byline: 0,
				show_title: 1,
				js_api: 1, // required in order to use the Javascript API
				js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
				js_swf_id: swf_id // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
			};
			var params = {
				allowscriptaccess: 'always',
				allowfullscreen: 'true',
				wmode: 'transparent'
			};
			var attributes = {};

			// For more SWFObject documentation visit: http://code.google.com/p/swfobject/wiki/documentation
			swfobject.embedSWF("http://vimeo.com/moogaloop.swf", swf_id, $el.width(), $el.height(), "9.0.0","expressInstall.swf", flashvars, params, attributes);
		});
	},
	handleTwitterComments: function() {
		function logged_in() {
			return $(".twitter-logged-in").size() > 0;
		}

		if (logged_in()) {
			$("#twitter_logout").bind('click', function(e) {
				e.preventDefault();
				$.cookie('oauth_token', '', { expires: -2, path: '/' });
				$.cookie('oauth_token_secret', '', { expires: -2, path: '/' });
				window.location.reload();
			});
		} else {
			$('.twitter-authenticate').show();
		}

		$indicator = $('#comment_message_characters');
		$('#comment_message').bind('keyup change', function(e) {
			len = $(this).val().length;
			count = 115 - len;
			if (count >= 0) {
				$indicator.html(sprintf('<strong>%d</strong> characters left', count));
			} else {
				$indicator.html(sprintf('You need to cut at least <strong>%d</strong> characters or we\'ll do that for you', -count));
			}
		});
	},
	moreItems: function($container, $list) {
		function isScrolledIntoView(elem) {
				var docViewTop = $(window).scrollTop();
				var docViewBottom = docViewTop + $(window).height();

				var elemTop = $(elem).offset().top;
				var elemBottom = elemTop + $(elem).height();

				return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
		}

		function handleScroll() {
			if (isScrolledIntoView($('#footer'))) {
				$(window).unbind('scroll');
				setTimeout(function() {
					page += 1;
					var url = $(window).attr('location').href;
					$.get(sprintf('%spage/%d/', url, page), function(data) {
						$temp = $('<div>').append(data);
						$temp = $temp.find('li');
						$temp.hide();
						images = [];
						$temp.find('img').each(function() {
							images.push($(this).attr('src'));
						});
						$list.append($temp);
						$.preLoadImages(images, function() { $temp.fadeIn(); });
						if (data.indexOf('last-page') == -1) {
							$(window).bind('scroll', handleScroll);
						}
					});
				}, 500);
			}
		}

		if ($container.find('.last-page').length == 0) {
			var page = 1;
			var $loader = $('<span class="ajax-loader">Loading</span>').hide();
			$loader.ajaxStart(function() { $(this).fadeIn(); });
			$loader.ajaxStop(function() { $(this).fadeOut(); });
			$container.append($loader);
			$(window).bind('scroll', handleScroll);
		}
	},
	locationMap: function() {
		var latlng = new google.maps.LatLng(34.392923, -119.519652);
		var options = {
			zoom: 16,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			streetViewControl: false
		};
		var $wrapper = $('<div />', { id: 'map-canvas', height: 291, width: 603 });
		$('#map-container').append($wrapper);

		Monokle.map = new google.maps.Map(document.getElementById("map-canvas"), options);

		var marker = new google.maps.Marker({
			position: latlng,
			map: Monokle.map,
			title: "Venture Visuals HQ"
		});
	},
	init: function() {
		Monokle.customTextfields();
		Monokle.replaceSubmits();
		onPage('page-home', function() { Monokle.createTopCarousel(true); });
		onPage('single-project', function() {
			Monokle.createTopCarousel();
			Monokle.embedProcessVideo();
		});
		onPage('page-company', function() { Monokle.createTopCarousel(); });
		onPage('single-post', function() {
			Monokle.createEntryCarousel();
			Monokle.handleTwitterComments();
		});
		onPage('custom-post-type-project-archive', function() {
			Monokle.moreItems($('#projects'), $('#projects .projects'));
		});
		onPage('blog', function() {
			Monokle.moreItems($('#entries'), $('#entries .entries'));
		});
		onPage('page-contact', function() {
			Monokle.locationMap();
		});
	}
}

$(Monokle.init);

// DD_belatedPNG fix for IE6
if (typeof DD_belatedPNG !== 'undefined') {
	var PNG_fix_selectors_hover = [
	];
	var PNG_fix_selectors = [
		'a.button',
		'a.button span',
		'.textfield',
		'.textfield-inner',
		'.textarea',
		'.textarea-inner',
		'.activity-feed .pic',
		'#team .photo',
		'#projects .categories a',
		'#projects .categories span',
		'#projects .projects li',
		'#details .process-video',
		'#details .people-involved',
		'#details .people-involved ul',
		'#entries .image',
		'#entry .meta .pic',
		'#carousel a.previous',
		'#carousel a.next'
	];
	DD_belatedPNG.fix(PNG_fix_selectors.join(','));
}

