/* Table of Contents

1. Scrolling News
2. Text Resizer
3. Equal Column Heights
4. Tool Tip
5. PNG Fix
6. Twitter Feed Reader

*/


/* 1. Scrolling News 
	------------------------------------------------------------------------------------------ */

/*
* Tadas Juozapaitis ( kasp3rito@gmail.com )
*/
(function($){
$.fn.vTicker = function(options) {
	var defaults = {
		speed: 2000,
		pause: 10000,
		showItems: 1,
		animation: '',
		mousePause: true,
		isPaused: false
	};

	var options = $.extend(defaults, options);

	moveUp = function(obj2, height){
		if(options.isPaused)
			return;
		
		var obj = obj2.children('ul');
		
    	first = obj.children('li:first').clone(true);
		
    	obj.animate({top: '-=' + height + 'px'}, options.speed, function() {
        	$(this).children('li:first').remove();
        	$(this).css('top', '0px');
        });
		
		if(options.animation == 'fade')
		{
			obj.children('li:first').fadeOut(options.speed);
			obj.children('li:last').hide().fadeIn(options.speed);
		}

    	first.appendTo(obj);
	};
	
	return this.each(function() {
		var obj = $(this);
		var maxHeight = 0;

		obj.css({overflow: 'hidden', position: 'relative'})
			.children('ul').css({position: 'absolute', margin: 0, padding: 0})
			.children('li').css({margin: 0, padding: 0});

		obj.children('ul').children('li').each(function(){
			if($(this).height() > maxHeight)
			{
				maxHeight = $(this).height();
			}
		});

		obj.children('ul').children('li').each(function(){
			$(this).height(maxHeight);
		});

		obj.height(maxHeight * options.showItems);
		
    	var interval = setInterval(function(){ moveUp(obj, maxHeight); }, options.pause);
		
		if(options.mousePause)
		{
			obj.bind("mouseenter",function(){
				options.isPaused = true;
			}).bind("mouseleave",function(){
				options.isPaused = false;
			});
		}
	});
};
})(jQuery);

/* 1. Scrolling News ------------------------------------------------------------------------------------------ */


/* 2. Text Resizer 
	------------------------------------------------------------------------------------------ */

/*
	jQuery Text Resizer plugin.
	
	Author: Mario J Vargas (angstrey at hotmail dot com)
	Website: http://angstrey.com/
	Documentation: http://angstrey.com/index.php/projects/jquery-text-resizer-plugin/
	
	Version: 1.0
	Revision History:
		* 2009-09-03: Version 1.0. Initial Release
*/
(function($) {
	var DEBUG_MODE = false;
	
	$.fn.t20_textresizer = function( options ) 
	{
	    if( DEBUG_MODE )
		    debug( this );
		
		// Stop plugin execution if no matched elements
		if( this.size() == 0 )
			return;

		// Default font sizes based on number of resize buttons.
		// "this" refers to current jQuery object
		var defaultSizes = buildDefaultFontSizes( this.size() );
	
		// Set up main options before element iteration
		var settings = $.extend( { selector: $(this).selector, sizes: defaultSizes, selectedIndex: -1 }, $.fn.t20_textresizer.defaults, options );

		// Ensure that the number of defined sizes is suitable
		// for number of resize buttons.
		if( this.size() > settings.sizes.length )
		{
		    if( DEBUG_MODE )
		    {
			    debug( 
				    "ERROR: Number of defined sizes incompatible with number of buttons => elements: " + this.size() 
				    + "; defined sizes: " + settings.sizes.length
				    + "; target: " + settings.target );
            }
               			
			return;	// Stop execution of the plugin
		}

		loadPreviousState( settings );
	
		// Iterate and bind click event function to each element
		return this.each( function( i ) {
			var $this = $(this);	// Current resize button
		
			var currSizeValue = settings.sizes[ i ];	// Size corresponding to this resize button
			
			// Mark this button as active if necessary
			if( settings.selectedIndex == i )
				$(this).addClass( "t20_textresizer-active" );
			
			// Apply the font size to target element when its 
			// corresponding resize button is clicked
			$this.bind( "click", { index: i }, function( e ) {		
				settings.selectedIndex = e.data.index;
				
				applyFontSize( currSizeValue, settings );
				saveState( currSizeValue, settings );

				markActive( this, settings );
			});
		});
	}
	
	// Default options of t20_textresizer plugin
	$.fn.t20_textresizer.defaults = {
		type  : "fontSize",	/* Available options: fontSize, css, cssClass */
		target: "body"		/* The HTML element to which the new font size will be applied */
	};

	function applyFontSize( newSize, settings )
	{
	    if( DEBUG_MODE )
		    debug( [ "target: " + settings.target, "newSize: " + newSize, "type: " + settings.type ].join( ", " ) );

		var targetElm = $( settings.target );
		switch( settings.type )
		{
			case "css":
				// Apply new inline CSS properties
				targetElm.css( newSize );
				break;

			case "cssClass":
				// Remove previously assigned CSS class from
				// target element. Iterating through matched
				// elements ensures the class is removed
				var cssClasses = settings.sizes;
				$.each( cssClasses, function( i, value ) {
					targetElm.each( function() {
						if( $(this).hasClass( value ) )
							$(this).removeClass( value );
					});
				});
				
				// Now apply the new CSS class
				targetElm.addClass( newSize );
				break;

			default:
				// Apply new font size
				targetElm.css( "font-size", newSize );
				break;
		}		
	}
	
	function markActive( sizeButton, settings )
	{
		// Deactivate previous button
		$(settings.selector).removeClass( "t20_textresizer-active" );
		
		// Mark this button as active
		$(sizeButton).addClass( "t20_textresizer-active" );
	}
	
	function buildCookieID( selector, target, prop )
	{
	    return "JQUERY.t20_textresizer[" + selector + "," + target + "]." + prop;
	}
	
	function getCookie( selector, target, prop )
	{
		var id = buildCookieID( selector, target, prop );
		
		var cookieValue = $.cookie( id );
		
		if( $.cookie( id + ".valueType" ) == "dict" && cookieValue )
		{
			var dict = {};
			var dictValues = cookieValue.split( "|" );
			
			for( var i = 0; i < dictValues.length; i++ )
			{
				// Separate key/value pair and assign to dictionary
				var keyValuePair = dictValues[ i ].split( "=" );
				dict[ keyValuePair[ 0 ] ] = unescape( keyValuePair[ 1 ] );
			}
			
			// Now that the object is finished, return it
			return dict;
		}
		
		return cookieValue;
    }
    
    function setCookie( selector, target, prop, value )
    {
		var id = buildCookieID( selector, target, prop );

		// Cookie expires in 1 year (365 days/year)
		var cookieOpts = { expires: 365, path: "/" };
		
		// Serialize value if it's an object
		if( typeof( value ) == "object" )
		{
		    // TODO: I think I wrote a JavaScript dictionary object serializer somewhere... Have to find it...
		    
			// Store type of value so we can convert it back 
			// to a dictionary object
			$.cookie( id + ".valueType", "dict", cookieOpts );

			var dict = value;	// (Assigning reference to variable dict for readability)
			var dictValues = new Array();
			for( var key in dict )
			{
				dictValues.push( key + "=" + escape( dict[ key ] ) );
			}

			var serializedVals = dictValues.join( "|" );
			$.cookie( id, serializedVals, cookieOpts );
			
			if( DEBUG_MODE )
			    debug( "In setCookie: Cookie: " + id + ": " + serializedVals );
		}
		else
		{
			$.cookie( id, value, cookieOpts );

            if( DEBUG_MODE )
			    debug( "In setCookie: Cookie: " + id + ": " + value );
		}
	}
	
	function loadPreviousState( settings )
	{
		// Determine if jquery.cookie is installed
		if( $.cookie )
		{
		    if( DEBUG_MODE )
			    debug( "In loadPreviousState(): jquery.cookie: INSTALLED" );

			var selectedIndex = getCookie( settings.selector, settings.target, "selectedIndex" );
			if( DEBUG_MODE )
			    debug( "In loadPreviousState: selectedIndex: " + selectedIndex + "; type: " + typeof(selectedIndex) );
			if( selectedIndex )
				settings.selectedIndex = selectedIndex;

			var prevSize = getCookie( settings.selector, settings.target, "size" );
			if( DEBUG_MODE )
			    debug( "In loadPreviousState: prevSize: " + prevSize + "; type: " + typeof(prevSize) );
			if( prevSize )
				applyFontSize( prevSize, settings );
		}
		else
		{
		    if( DEBUG_MODE )
			    debug( "In loadPreviousState(): jquery.cookie: NOT INSTALLED" );
		}
	}
	
	function saveState( newSize, settings )
	{
		// Determine if jquery.cookie is installed
		if( $.cookie )
		{
			if( DEBUG_MODE )
			    debug( "In saveState(): jquery.cookie: INSTALLED" );
			
			setCookie( settings.selector, settings.target, "size", newSize );
			setCookie( settings.selector, settings.target, "selectedIndex", settings.selectedIndex );
		}
		else
		{
			if( DEBUG_MODE )
			    debug( "In saveState(): jquery.cookie: NOT INSTALLED" );
		}
	}
	
	function debug( $obj )
	{
		if( window.console && window.console.log )
		{
			if( typeof( $obj ) == "string" )
				window.console.log( "jquery.t20_textresizer => " + $obj );
			else	// Assumes $obj is jQuery object
				window.console.log( "jquery.t20_textresizer => selection count: " + $obj.size() );
		}
	}
	
	function buildDefaultFontSizes( numElms )
	{
		var size0 = 14;				/* Initial size, measured in pixels */
		
		var mySizes = new Array();
		
		if( DEBUG_MODE )
		    debug( "In buildDefaultFontSizes: numElms = " + numElms );
		
		if( DEBUG_MODE )
		{
		    for( var i = 0; i < numElms; i++ )
		    {
			    // Append elements in increments of 2 units
			    var value = (size0 + (i * 2)) / 10;
			    mySizes.push( value + "em" );	
    			
			    if( DEBUG_MODE )
			        debug( "In buildDefaultFontSizes: mySizes[" + i + "] = " + mySizes[ i ] );
		    }
		}
		else
		{
		    for( var i = 0; i < numElms; i++ )
		    {
			    // Append elements in increments of 2 units
			    var value = (size0 + (i * 2)) / 10;
			    mySizes.push( value + "em" );	
		    }
		}
		
		return mySizes;
	}
})(jQuery);

/* 2. Text Resizer  ------------------------------------------------------------------------------------------ */




/* 3. Equal Column Heights  
------------------------------------------------------------------------------------------ */
function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

/* 3. Equal Column Heights  ------------------------------------------------------------------------------------------ */



/* 4. Tool Tip 
	------------------------------------------------------------------------------------------ */
/*
 * Tooltip script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 


this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.t20_toolTip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<div id='t20_toolTip'><div class='t20_toolTipBox'><div class='t20_boxTop'></div><div class='t20_boxContent'>"+ this.t +"</div><div class='t20_boxBot'></div></div></div>");
		$("#t20_toolTip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#t20_toolTip").remove();
    });	
	$("a.t20_toolTip").mousemove(function(e){
		$("#t20_toolTip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};



// starting the script on page load
$(document).ready(function(){
	tooltip();
});


/* 4. Tool Tip ------------------------------------------------------------------------------------------ */

/*
 * 	Easy Tooltip 1.0 - jQuery plugin
 *	written by Alen Grakalic	
 *	http://cssglobe.com/post/4380/easy-tooltip--jquery-plugin
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */
 
(function($) {

	$.fn.easyTooltip = function(options){
	  
		// default configuration properties
		var defaults = {	
			xOffset: 10,		
			yOffset: 25,
			tooltipId: "easyTooltip",
			clickRemove: false,
			content: "",
			useElement: ""
		}; 
			
		var options = $.extend(defaults, options);  
		var content;
				
		this.each(function() {  				
			var title = $(this).attr("title");				
			$(this).hover(function(e){											 							   
				content = (options.content != "") ? options.content : title;
				content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
				$(this).attr("title","");									  				
				if (content != "" && content != undefined){			
					$("body").append("<div id='"+ options.tooltipId +"'>"+ content +"</div>");		
					$("#" + options.tooltipId)
						.css("position","absolute")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX + options.xOffset) + "px")						
						.css("display","none")
						.fadeIn("fast")
				}
			},
			function(){	
				$("#" + options.tooltipId).remove();
				$(this).attr("title",title);
			});	
			$(this).mousemove(function(e){
				$("#" + options.tooltipId)
					.css("top",(e.pageY - options.yOffset) + "px")
					.css("left",(e.pageX + options.xOffset) + "px")					
			});	
			if(options.clickRemove){
				$(this).mousedown(function(e){
					$("#" + options.tooltipId).remove();
					$(this).attr("title",title);
				});				
			}
		});
	  
	};

})(jQuery);




/* 5. jQuery-Plugin "pngFix" 
------------------------------------------------------------------------------------------ */

/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.2, 09.03.2009
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 *                      http://jquery.andreaseberhard.de/
 *						http://jquery.andreaseberhard.de/pngFix/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Changelog:
 *    09.03.2009 Version 1.2
 *    - Update for jQuery 1.3.x, removed @ from selectors
 *    11.09.2007 Version 1.1
 *    - removed noConflict
 *    - added png-support for input type=image
 *    - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
 *    31.05.2007 initial Version 1.0
 * --------------------------------------------------------------------
 * @example $(function(){$(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready
 *
 * jQuery(function(){jQuery(document).pngFix();});
 * @desc Fixes all PNG's in the document on document.ready when using noConflict
 *
 * @example $(function(){$('div.examples').pngFix();});
 * @desc Fixes all PNG's within div with class examples
 *
 * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
 * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
 * --------------------------------------------------------------------
 */

(function($) {

jQuery.fn.pngFix = function(settings) {

	// Settings
	settings = jQuery.extend({
		blankgif: 'blank.gif'
	}, settings);

	var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

	if (jQuery.browser.msie && (ie55 || ie6)) {

		//fix images with png-source
		jQuery(this).find("img[src$=.png]").each(function() {

			jQuery(this).attr('width',jQuery(this).width());
			jQuery(this).attr('height',jQuery(this).height());

			var prevStyle = '';
			var strNewHTML = '';
			var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
			var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
			var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
			var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
			var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
			var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
			if (this.style.border) {
				prevStyle += 'border:'+this.style.border+';';
				this.style.border = '';
			}
			if (this.style.padding) {
				prevStyle += 'padding:'+this.style.padding+';';
				this.style.padding = '';
			}
			if (this.style.margin) {
				prevStyle += 'margin:'+this.style.margin+';';
				this.style.margin = '';
			}
			var imgStyle = (this.style.cssText);

			strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
			strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
			strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
			strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
			strNewHTML += imgStyle+'"></span>';
			if (prevStyle != ''){
				strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
			}

			jQuery(this).hide();
			jQuery(this).after(strNewHTML);

		});

		// fix css background pngs
		jQuery(this).find("*").each(function(){
			var bgIMG = jQuery(this).css('background-image');
			if(bgIMG.indexOf(".png")!=-1){
				var iebg = bgIMG.split('url("')[1].split('")')[0];
				jQuery(this).css('background-image', 'none');
				jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
			}
		});
		
		//fix input with png-source
		jQuery(this).find("input[src$=.png]").each(function() {
			var bgIMG = jQuery(this).attr('src');
			jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
   		jQuery(this).attr('src', settings.blankgif)
		});
	
	}
	
	return jQuery;

};

})(jQuery);


/* 6. Twitter Feed Reader
------------------------------------------------------------------------------------------ */
(function($){
 	$.fn.extend({ 
		//pass the options variable to the function
 		jtwt: function(options) {

			//Set the default values, use comma to separate the settings, example:
			var defaults = {
				username : 'google',
                count : 1,
                image_size: 48,
                convert_links: 1,
                loader_text: 'loading new tweets'
			}
				
			var options =  $.extend(defaults, options);

    		return this.each(function() {
				var o = options;
                var obj = $(this);  
                
$(obj).append('');	
$("#jtwt_loader").fadeIn('slow');

						$.getJSON('http://twitter.com/status/user_timeline/' + o.username + '.json?count=' + o.count + '&callback=?', function(data){ 

			$.each(data, function(i, item) {       
            
                
				jtweet = '<li>';
                
                if (o.image_size != 0) {
                
                today = new Date();
  
                jtweet += '<div id="jtwt_picture">';
                jtweet += '<a href="http://twitter.com/' + item.user['screen_name'] + '">'
                jtweet += '<img width="' + o.image_size +'" height="' + o.image_size + '" src="' + item.user['profile_image_url'] + '" />';
                jtweet += '</a>';
                jtweet += '</div>';
                } 

               
                var tweettext = item.text;
                var tweetdate = item.created_at;
                
                if (o.convert_links != 0) {
                  
                tweettext = tweettext.replace(/(http\:\/\/[A-Za-z0-9\/\.\?\=\-]*)/g,'<a href="$1" class="npd_twtLinkTwo" target="_blank">$1</a>');
                tweettext = tweettext.replace(/@([A-Za-z0-9\/_]*)/g,'<a href="http://twitter.com/$1" class="npd_twtLinkTwo" target="_blank">@$1</a>');
                tweettext = tweettext.replace(/#([A-Za-z0-9\/\.]*)/g,'<a href="http://twitter.com/search?q=$1" class="npd_twtLinkTwo" target="_blank">#$1</a>');
                
                }
                
                tweetdate = tweetdate.replace(/201.{1}/, "");
                tweetdate = tweetdate.replace(/\+00.{2}/, "");
                jtweet += '<a href="http://twitter.com/' + item.user['screen_name'] + '/statuses/' + item.id + '" class="npd_twtLinkOne" target="_blank">';
				jtweet += tweettext;
                jtweet += '</a></li>';

   				$(obj).append(jtweet);

          		 });   
                 

$("#jtwt_loader").fadeOut('fast');   
           
		});

    		});
    	}
	});
	
})(jQuery);

