/**
 * @author Dextro
 */
function showHelp(divId){
    Effect.Appear(divId, {
        duration: 0.3,
        queue:  { position: 'end', scope: divId } 
    });
}

function hideHelp(divId){
    Effect.Fade(divId, {
        duration: 0.2,
        queue:  { position: 'end', scope: divId }
    });
}

function onSearchFocus(event){
    showHelp('search-help');
    
    var $placeholder = this.readAttribute('placeholder');
    
    if (this.value == $placeholder) {
        this.value = '';
    }
}

function onSearchBlur(event){
    hideHelp('search-help');
    
    if (this.value == '') {
    	var $placeholder = this.readAttribute('placeholder');
    	
        this.value = $placeholder;
    }
}

function onSelectorClick(event){
    var $element = $$(this.readAttribute('href')).first();
    
    if (!$element.visible()) {
        $$('#contents article').each(function(article, n){
            if (article.visible()) {
                Effect.SlideUp(article, {
                    duration: 0.5,
                    queue: {
                        position: 'end',
                        scope: 'portfolio'
                    }
                });
            }
        });
        
        Effect.SlideDown($element, {
            duration: 0.8,
            queue: {
                position: 'end',
                scope: 'portfolio'
            }
        });
        
        $$('#contents nav li .selected').each(function(nav, n){
            nav.removeClassName('selected');
        })
        
        this.addClassName('selected');
    }
    
    Event.stop(event);
}

function append_smilies(){
    var $img_location = "/wp-includes/images/smilies/";
    var $smilies = $H({
        ":mrgreen:": "icon_mrgreen.gif",
        ":|": "icon_neutral.gif",
        ":twisted:": "icon_twisted.gif",
        ":arrow": "icon_arrow.gif",
        "8O": "icon_eek.gif",
        ":)": "icon_smile.gif",
        ":?": "icon_confused.gif",
        "8)": "icon_cool.gif",
        ":evil:": "icon_evil.gif",
        ":D": "icon_biggrin.gif",
        ":idea:": "icon_idea.gif",
        ":oops:": "icon_redface.gif",
        ":P": "icon_razz.gif",
        ":roll:": "icon_rolleyes.gif",
        ";)": "icon_wink.gif",
        ":cry:": "icon_cry.gif",
        ":o": "icon_surprised.gif",
        ":lol:": "icon_lol.gif",
        ":x": "icon_mad.gif",
        ":(": "icon_sad.gif",
        ":!:": "icon_exclaim.gif",
        ":?:": "icon_question.gif"
    });
    
    var $div = new Element('div').addClassName('smilies-wrapper');

    var $p = new Element('p').addClassName('smilies').addClassName('border');
    $smilies.each(function($item){
        $link = new Element('a').writeAttribute('rel', $item.key).writeAttribute('href', "#").observe('click', add_smilie);
        $image = new Element('img').addClassName('wp-smiley').writeAttribute('title', $item.key).writeAttribute('alt', $item.key).writeAttribute('src', $img_location + $item.value);
        $link.insert($image);
        $p.insert($link);
    });

    $div.insert($p);

    $('comment-text').up().insert({
        after: $div
    });
}

function add_smilie(event){
    var $form = $('comment-text');
    $form.setValue($form.getValue() + " " + this.readAttribute('rel') + " ");
    Event.stop(event);
}

function on_comment_reply_link(event) {
	var $id = this.readAttribute('href').toQueryParams()['replytocom'];
	$("cancel-comment-reply-link").show();
	$("comment_parent").writeAttribute('value', $id);
	Effect.ScrollTo('respond');
	Event.stop(event);
}

function on_cancel_comment_reply_link(event) {
	this.fade({duration: 0.2});
	$("comment_parent").writeAttribute('value', '0');
	Event.stop(event);
}

function stop_idle_effects() {
	var queue = Effect.Queues.get('help-idle');
	queue.each(function(effect) { effect.cancel(); });
}

function on_help_over(event) {
	stop_idle_effects();
	this.fade({duration: 8.0, to: 0.1, queue: { scope: 'help-idle' } });
}

function on_help_out(event) {
	stop_idle_effects();
	this.fade({duration: 0.1, to: 1.0, queue: { scope: 'help-idle' } });
}

function onArchivesMenuClick(event) {
	var $element = $$(this.readAttribute('href')).first();
	
	$$('#archives-menu li').each(function(item) {
		item.removeClassName('selected');
	});
	
	this.up().addClassName('selected');

	$$('#archive-content > div').each(function(item) {
		if (item.visible() && item != $element) {
			Effect.Fade(item.identify(), {
				duration : 0.5,
				queue : {
					position : 'end',
					scope : 'archives-menu'
				}
			});
		}
	});

	Effect.Appear($element.identify(), {
		duration : 0.5,
		queue : {
			position : 'end',
			scope : 'archives-menu'
		}
	});
	
	this.blur();
	
	event.stop();
}

var HIGHLIGHTTIME = 30;
var $highlightTimer;
var $highlightProgressTimer;

function highlightChange(pe) {
	$highlightTimer.currentlyExecuting = true;
	var $articles = $$('.related-list');

	$articles.each(function(obj) {
		var $hidden = false;
		var $shown = false;
		var $prevlink = obj.down('.back');
		var $nextlink = obj.down('.forward');
		
		var $entries = Selector.findChildElements(obj, ['.entry']);
		var $i = $entries.length;

		$entries.each(function(item) {
			if (item.visible() && !$hidden) {
				item.hide();
				$hidden = true;
			} else if (!item.visible() && $hidden && !$shown) {
				item.show();
				$shown = true;
				$prevlink.show();
			}
			if (!$shown) {
				$i--;
			}
		});
		if (!$shown) {
			$entries[0].show();
			$prevlink.hide();
		}
		if ($i == 1) {
			$nextlink.hide();
		} else {
			$nextlink.show();
		}
	});
	
	resetHighlightProgress();
	
	$highlightTimer.currentlyExecuting = false;
}

function resetHighlightProgress() {
	$highlightProgressTimer.cancel();
	$$('.related-list .progress .bar').each(function(item) {
		item.setStyle({
			'width' : "1px"
		});	

		$highlightProgressTimer = new Effect.Morph(item, {
								style: 'width: 100%',
								transition: Effect.Transitions.linear,
								duration: HIGHLIGHTTIME
							});
	});
}

var $highlightOver = false;

function highlightOut(event) {
	if ($highlightOver) {
		$highlightOver = false;
		$highlightTimer = new PeriodicalExecuter(highlightChange, HIGHLIGHTTIME);

		if ("undefined" === typeof($bar)) {
			$bar = this.down('.bar');
		}

		$bar.setStyle({
			'width' : "1px"
		});

		$highlightProgressTimer.cancel();
		$highlightProgressTimer = new Effect.Morph($bar, {
								style: 'width: 100%',
								transition: Effect.Transitions.linear,
								duration: HIGHLIGHTTIME
							});
	}
}

function highlightOver(event, $bar) {
	if (!$highlightOver) {
		$highlightOver = true;
		$highlightTimer.stop();
		$highlightProgressTimer.cancel();

		if ("undefined" === typeof($bar)) {
			$bar = this.down('.bar');
		}

		new Effect.Morph($bar, {
								style: 'width: 1%',
								transition: Effect.Transitions.sinoidal,
								duration: 0.3
							});
	}
}

function highlightNext(event) {
	highlightOver(event, this.up('.related-list').down('.bar'));
	
	var $list = this.up('.related-list');
	var $articles = Selector.findChildElements($list, ['.entry']);

	var $i = 0;
	while ($i < $articles.length && !$articles[$i].visible()) {
		$i++;
	}
	$articles[$i++].hide();
	$articles[$i++].show();

	if ($i >= $articles.length) {
		$list.down('.forward').hide();
	}
	$list.down('.back').show();

	resetHighlightProgress();
	highlightOut(event, this.up('.related-list').down('.bar'));
	
	event.stop();
}

function highlightPrevious(event) {
	highlightOver(event, this.up('.related-list').down('.bar'));
	
	var $list = this.up('.related-list');
	var $articles = Selector.findChildElements($list, ['.entry']);

	var $i = $articles.length - 1;
	while ($i > 0 && !$articles[$i].visible()) {
		$i--;
	}
	$articles[$i--].hide();
	$articles[$i--].show();

	if ($i < 0) {
		$list.down('.back').hide();
	}
	$list.down('.forward').show();
	
	resetHighlightProgress();
	highlightOut(event, this.up('.related-list').down('.bar'));

	event.stop();
}

function socialShare(event) {
	var $link = this.readAttribute('href');
	var $socialWindow = window.open($link, '_blank',
			'width=780,height=640');
	if (window.focus) {
		$socialWindow.focus();
	}
	
	event.stop();
}

var $langTitle = "English not Available";
var $langText = "Some bits of the website are not available in english and this is one of them.";
function langOver(event) {
	var $div = new Element('div', {
		'id' : 'lang-popup'
	});
	
	$div.insert(new Element('h1').update($langTitle));
	$div.insert(new Element('p').update($langText));
	
	var $wrapper = new Element('div', {
		'id' : 'lang-popup-wrapper'
	});
	
	$wrapper.insert($div);
	
	var $offset = this.cumulativeOffset();
	
	$wrapper.setStyle({
		'left' : ($offset.left + this.getHeight() - 5) + "px",
		'top' : ($offset.top + this.getHeight() - 5) + "px"
	});
	
	$('global-wide').insert({
		after : $wrapper
	});
}

function langOut(event) {
	$('lang-popup-wrapper').remove();
}

Event.observe(window, 'load', function(){
    if ($('search-help')) 
        $('search-help').hide();
    
    if ($('s')) {
        Event.observe($('s'), 'focus', onSearchFocus);
        Event.observe($('s'), 'blur', onSearchBlur);
    }

    if ($('comments-write')) {
		if ($$('.comments-list .depth-2')) {
			$$('.comments-list .depth-1').each(function(item) {
			    var $link = item.down('.comment-reply-link');
		    	var $i = 0;
			    var $child;
			    while($child = item.down('.depth-2 .meta .date-time', $i++)) {
			        var $link_copy = $link.clone(1);
		        	$child.insert({
		    	        after: $link_copy
			        });
			        $link_copy.insert({
			            before: " [",
		            	after: "] "
		        	});
		    	}
			});		
		}

    	$$('.comment-reply-link').each(function(link, n){
    		link.removeAttribute('onclick');
    		Event.observe(link, 'click', on_comment_reply_link);
    	});
    	
    	$("cancel-comment-reply-link").observe('click', on_cancel_comment_reply_link);
    	
        $$('#comments-write .input, #comments-write .textarea').each(function(field, n){
            Event.observe(field, 'focus', function(){
                showHelp('help-' + field.identify());
            });
            Event.observe(field, 'blur', function(){
                hideHelp('help-' + field.identify());
            });
        });
        
        $$('#comments-help h3').each(function(title){
            title.hide()
        });
        $$('#comments-help .help').each(function(div){
            div.addClassName('popup');
            div.observe('mouseover', on_help_over);
            div.observe('mouseout', on_help_out);
            div.hide();
        });

		/* Screw IE! */
		if (!Prototype.Browser.IE) {
			$$('#comments-write .input, #comments-write .textarea').each(function(field, n){
				$help_div = $('help-' + field.identify());
				$offset = $help_div.getHeight() * -1;
				$help_div.clonePosition(field, {
					offsetTop: $offset,
					offsetLeft: 0,
					setHeight: false,
					setWidth: false,
					setLeft: false
				});
			});
		}
        
        append_smilies();
    }

	var $wrapperHeight = 0;

    if ($('portfolio')) {
		$wrapperHeight = 0;

        $$('#contents article').each(function(article, n){
            if (article.getHeight() > $wrapperHeight) {
                $wrapperHeight = article.getHeight();
            }
            article.hide();
            article.firstDescendant().relativize();
        }).first().show();
        
        $$('#contents nav li a').each(function(selector, n){
            Event.observe(selector, 'click', onSelectorClick);
        }).first().addClassName('selected');
        
        $('articles-wrapper').setStyle({
            height: ($wrapperHeight + 5) + 'px'
        });
    }
    
    if ($('archives-menu')) {
    	$$('#archives-menu li').each(function(item) {
    		item.down('a').observe('click', onArchivesMenuClick);
    	}).first().addClassName('selected');

		$wrapperHeight = 0;
    	
    	$$('#archive-content > div').each(function(item){
			if (item.getHeight() > $wrapperHeight) {
				$wrapperHeight = item.getHeight();
				$('archive-content').setStyle({
					'height' : ($wrapperHeight + 24) + 'px'
				});
			}
    		item.hide();
        }).first().show();
    }
  
	/* Screw IE again! */
    if ($$('.related') && !Prototype.Browser.IE) {
    	$$('.related, .related-list').each(function(item) {
    		item.addClassName('flashy');
    	});
    	
    	$$('.related-list .highlight-img').each(function(item) {
    		item.show();
    	});
    	
    	$$('.related-list').each(function(item) {
    		var $prev = new Element('li', {
    			'class' : 'back'
    		}).insert(new Element('a', {
    				'href' : "#"
   			}).update("&lt;").observe('click', highlightPrevious));

    		var $next = new Element('li', {
    			'class' : 'forward'
    		}).insert(new Element('a', {
    				'href' : "#"
   			}).update("&gt;").observe('click', highlightNext));
    		
			var $bar = new Element('span', {
    				'class' : 'bar'
   			}).update("&nbsp;").setStyle({
    				'width' : '1%'
   			});
    		var $progress = new Element('li', {
    			'class' : 'progress'
    		}).insert($bar);
    		
    		item.insert($prev);
    		$prev.hide();
    		item.insert($next);
    		item.insert($progress);
    		
    		var $first = true;
    		item.childElements().each(function(obj) {
    			if (obj.hasClassName('entry')) {
    				if (!$first) {
    					obj.hide();
    				} else {
    					$first = false;
    					obj.show();
    				}
    			}
    		});

			if (item.childElements().length <= (1 + 3)) {
				$next.hide();
				$progress.hide();
			} else {
	    		$highlightTimer = new PeriodicalExecuter(highlightChange, HIGHLIGHTTIME);
				$highlightProgressTimer = new Effect.Morph($bar, {
							style: 'width: 100%',
							transition: Effect.Transitions.sinoidal,
							duration: HIGHLIGHTTIME
						});
    			item.observe('mouseover', highlightOver);
    			item.observe('mouseout', highlightOut);
			}
    		
    		item.observe('')
    	});
    }

	$$('.post-options .social .buzz a, .post-options .social .facebook a, .post-options .social .twitter a').each(function(item) {
		item.observe('click', socialShare);
	});

    $$('a[rel^="lightbox"]').each(function(link, n){
        link.addClassName('lightview');
        var $rel = link.readAttribute('rel');
        if ($rel.length > 9) {
            $rel = $rel.substring(9, ($rel.length - 1));
            link.writeAttribute('rel', 'gallery[' + $rel + ']');
        }
        else {
            link.writeAttribute('rel', '');
        }
    });

	$$('div.gallery').each(function(item) {
		var $galleryId = item.identify();
		var $galleryItem = item.down('.gallery-item');
		
		do {
			$link = $galleryItem.down('a');
			$link.writeAttribute('rel', 'gallery[' + $galleryId + ']');
			$link.addClassName('lightview');
			$galleryItem = $galleryItem.next('.gallery-item');
		}while($galleryItem);
	});
	
	if (!Prototype.Browser.IE) {
		$$('.no-english').each(function(item) {
			item.observe('mouseover', langOver);
			item.observe('mouseout', langOut);
		});
	}	
});

