//function to check if an attribute is supported

function elementSupportsAttribute(element,attribute) { 
	var test = document.createElement(element);
	if (attribute in test) {
		return true; 
	} else {
		return false;
	}
}

//dynamically load javascript file
function jsAppend(js_file) {
	js_script = document.createElement('script');
	js_script.type = "text/javascript";
	js_script.src = js_file;
	document.getElementsByTagName('head')[0].appendChild(js_script);
}

//look for a placeholder attribute and 
//load jquery watermark plugin if it doesn't exist

if (!elementSupportsAttribute('input','placeholder')) {
	jsAppend('javascripts/jquery.watermark.min.js');
	$(function(){
		$('input[placeholder], textarea[placeholder]').each(function(){
			$(this).watermark($(this).attr('placeholder'));
		});
	});
}

// Select Replacement plugin
// Version: 0.2
// Author: Mladen Stepanic
/*
	you can specify placeholder elements by putting it in array. those words or phrases will not be added to the list
	but will show up if nothing is selected. However, you must add them in the first <option> in select
*/
	var methods = {
		'init': 		function( obj ){
							//loop through every element
							this.each(function(){
								//and return proper html for every select
								var selected_index = $(this).get(0).selectedIndex;
								$(this).find('option').eq(selected_index).addClass('selected');	
								return 	$(this)
										.hide()
										.wrap('<span class="selectWrapper '+$(this).attr('class')+'"/>')
										.before('<a class="replaced" href="#" tabindex="1">'+$(this).find('option').eq(selected_index).html()+'</a>')
										.parent().css({
											"display":"-moz-inline-stack",
											"display":"inline-block",
											"*display":"inline",
											"zoom":1,
											"position":"relative"
										});
							});
						},
		'createDD': 	function( obj ) {
							//search for string in array
							function oc(a){
							  var o = {};
							  for(var i=0;i<a.length;i++)
							  {
								o[a[i]]='';
							  }
							  return o;
							}			

							//keyboard controls for dropdown elements;
							
							function keyboard_controls(){								
								$(document).bind('keydown', function(e){
									e.preventDefault();
									switch (e.keyCode) {
										case 13:
											//enter selects current list item
											$(".repDD a.selected").click();
											break;
										case 38:
											//up arrow
											if( $(".repDD a.selected").parent().index() != 0 ) {
												$(".repDD a.selected").removeClass('selected').parent().prev().find('a').addClass('selected');
												move_list();
											}
											break;
										case 40:
											//down arrow
											var count = $(".repDD li").length;
											if(  $(".repDD a.selected").parent().index() < (count -1) ) {
												$(".repDD a.selected").removeClass('selected').parent().next().find('a').addClass('selected');
												move_list();
											}else{
												return false;
											}
											break;
										case 27:
											closeDD();
											break;
										default:
											return false;
									}
									
								});
							}
							
							function move_list() {
								var list_offset = Math.round($('.repDD').offset().top);
								var list_item_offset = Math.round($(".repDD a.selected").offset().top);
								var list_bottom = Math.round($('.repDD').offset().top) + $('.repDD').height();								
								
								if( (list_offset < list_item_offset) && (list_item_offset < list_bottom) ){
								}else{
									$(".repDD").scrollTo($('.repDD a.selected'), 200);
								}
							}
							//add/remove active button classes
							function hover_on_list () {
								$(".repDD a").mouseover(function(){
									$(this).closest('ul').find('a').removeClass("selected");
									$(this).addClass('selected');
								});
							}
							
							//open dropdown							
							function openDD(){
								var wrapper = $(".repDD").parent();
								if(transition == 'slide'){
									$('.repDD').animate({"height":'show'}, transitionSpeed, 
										function(){
											bindClose();
											$(wrapper).css({"z-index":99999});
											keyboard_controls();
											hover_on_list ()
										}
									);
								}else if (transition == 'fade'){
									$('.repDD').fadeIn(transitionSpeed, 
										function(){
											bindClose();
											$(wrapper).css({"z-index":99999});
											keyboard_controls();
											hover_on_list ()
										}
									);
								}

								
								//actually select new value for your <select>
								$(".replaced_dropdown a").click(function(e){
									e.preventDefault();
									var th_is = $(this);
									var sel_value = $(this).attr("data-value");
									var wrapper = $(this).parents('.selectWrapper');
									var select_obj = $(wrapper).find('select');
									$(wrapper).css({"z-index":''});
									$(select_obj)
										.val(encodeURIComponent(sel_value))
										.trigger('change')
										.siblings('.replaced')
										.html($(th_is).html());
									//set current option
									$(this)
										.parents('.selectWrapper')
										.find('option.selected')
										.removeClass('selected');
									$(this)
										.parents('.selectWrapper')
										.find('option[value="'+sel_value+'"]')
										.addClass('selected');
									closeDD();
								});
							}
							
							//close dropdown
							function closeDD (){
								if(transition == 'slide'){
									var wrapper = $(".repDD").parent();
									$('.repDD').animate({'height':'hide'}, transitionSpeed, function(){
										$(this).remove(); 
										$(wrapper).css({"z-index":''});
									});
								}else if(transition == 'fade'){
									$('.repDD').fadeOut(transitionSpeed, function(){
										$(this).remove();
										$(wrapper).css({"z-index":''});
									});
								}
								$(document).unbind('click');
								$(document).unbind('keydown');
							}
							
							//watches for clicked element's parent. if .selectWrapper is found, close dropdown
							function bindClose(){
								$(document).bind('click', function(e){
									if(($(e.target).parents('.repDD').length !== 1) && ($(e.target).attr('class') !== 'replaced' )){
										closeDD();
									}else{
									}
								});
							}

							
							var list_item = '';
							var placeholders = methods.options.placeholders;
							var transition = methods.options.transition;
							var transitionSpeed = methods.options.transitionSpeed;	
							
							if( $(this).siblings('div').css('display') == 'block' ) {
								closeDD();
							}else{
								
								$('.repDD').remove();
								
								var dropdown_string = [
										'<div class="repDD" style="display:none">',
											'<div class="list_wrapper">',
												'<ul class="replaced_dropdown" />',
											'</div>',
										'</div>'						
								].join('');		
							
								
								//filter out any placeholder words
								var options = $(this).siblings('select').find('option');
								$(options).each(function(){
									if ( !($(this).val().toLowerCase() in oc(placeholders))){
										if( $(this).attr('data-icon')){
											if($(this).hasClass('selected')){											
												list_item += '<li><a class="selected" href="#" data-value="'+$(this).val()+'"><img src="'+$(this).attr('data-icon')+' />"'+$(this).html()+'</a></li>';
											}else{
												list_item += '<li><a href="#" data-value="'+$(this).val()+'"><img src="'+$(this).attr('data-icon')+'" />'+$(this).html()+'</a></li>';											
											}
										}else{
											if($(this).hasClass('selected')){											
												list_item += '<li><a class="selected" href="#" data-value="'+$(this).val()+'">'+$(this).html()+'</a></li>';
											}else{
												list_item += '<li><a href="#" data-value="'+$(this).val()+'">'+$(this).html()+'</a></li>';											
											}										
										}
									}
								});

								//add empty list html code after newly created dropdown
								$(this).after(dropdown_string)
									.siblings('.repDD')
									.find('.replaced_dropdown')
									.append(list_item).closest(".repDD");
								
								openDD();

							}
							return this;
						},
		'options':		{
				//put placeholder words in lowercase!!!
				'placeholders' 		:	['please select'],
				'transition'		:	'fade',
				'transitionSpeed'	:	400
			},
		'destroyFn': function( obj ){
						//in case you want to remove selects
						$('.replaced, .repDD').remove();
						this.unwrap('<span class="selectWrapper" />').show();
						
					}
	};

	
	
	$.fn.replaceSelect = function( settings ){
		if( settings ) {
			//if there are settins specified, use them
			$.fn.extend( methods.options, settings );
		}else{
			//if not, use default settings
			settings = methods.options;
		}
		if((settings.destroy) && (settings.destroy == true)){
			return methods.destroyFn.apply(this);
		}else{
		
			var init = methods.init.apply(this, Array.prototype.slice.call(arguments, 1));
			
			var click_evt = $(".replaced").click(function(e){
								e.preventDefault();
								var create =  methods.createDD.apply(this);	
								return (create);
							});
			var initial_settings = [
				init, click_evt
			];
		
			return initial_settings;
		}
	}; 


	
	
	
//this part is jquery scrollTo plugin

/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 */
 
 ;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery )



$(function(){
	//replace select boxes with something prettier :)
	$("select").replaceSelect({
		placeholders: ['popular cities', 'cuisine types']
	});
	
	//add page curl effect to post images
	$(".post figure").each(function(){
		$(this).append('<span class="curl" />');
	});
	
	//hide and show +1 in vote box
	$(".hots").hover(
		function(){
			$(this).find('.hots_plus_one').removeClass('hide').siblings('.hots_no').addClass('hide');
		},
		function(){
			$(this).find('.hots_plus_one').addClass('hide').siblings('.hots_no').removeClass('hide');
	 	});
});
