/*
 * jQuery LiveTwitter 1.7.3
 * - Live updating Twitter plugin for jQuery
 *
 * Copyright (c) 2009-2011 Inge Jørgensen (elektronaut.no)
 * Licensed under the MIT license (MIT-LICENSE.txt)
 *
 * $Date: 2011/10/28$
 */

/*jslint browser: true, devel: true, onevar: false, immed: false, regexp: false, indent: 2 */
/*global window: false, jQuery: false */

/*
 * Usage example:
 * $("#twitterSearch").liveTwitter('bacon', {limit: 10, rate: 15000});
 */


(function ($) {

  // Extend jQuery with a reverse function if it isn't already defined
  if (!$.fn.reverse) {
    $.fn.reverse = function () {
      return this.pushStack(this.get().reverse(), arguments);
    };
  }
  
  $.fn.liveTwitter = function (query, options, callback) {
    var domNode = this;
    $(this).each(function () {
      var settings = {};

      // Does this.twitter already exist? Let's just change the settings.
      if (this.twitter) {
        settings = $.extend(this.twitter.settings, options);
        this.twitter.settings = settings;
        if (query) {
          this.twitter.query = query;
        }
        if (this.twitter.interval) {
          this.twitter.refresh();
        }
        if (callback) {
          this.twitter.callback = callback;
        }

      // ..if not, let's initialize.
      } else {

        // These are the default settings.
        settings = $.extend({
          mode:      'search', // Mode, valid options are: 'search', 'user_timeline', 'list', 'home_timeline'
          rate:      15000,    // Refresh rate in ms
          limit:     10,       // Limit number of results
          imageSize: 24,       // Size of image in pixels
          refresh:   true,
          timeLinks: true,
          replies:   true,
          retweets:  false,
          service:   false,
          localization: {
            seconds: 'seconds ago',
            minute:  'a minute ago',
            minutes: 'minutes ago',
            hour:    'an hour ago',
            hours:   'hours ago',
            day:     'a day ago',
            days:    'days ago'
          }
        }, options);
        // showAuthor should default to true unless mode is 'user_timeline'.
        if (typeof settings.showAuthor === "undefined") {
          settings.showAuthor = (settings.mode === 'user_timeline') ? false : true;
        }

        // Set up a dummy function for the Twitter API callback.
        if (!window.twitter_callback) {
          window.twitter_callback = function () {
            return true;
          };
        }

        this.twitter = {
          settings:      settings,
          query:         query,
          interval:      false,
          container:     this,
          lastTimeStamp: 0,
          callback:      callback,

          // Convert the time stamp to a more human readable format
          relativeTime: function (timeString) {
            var parsedDate = Date.parse(timeString);
            var delta = (Date.parse(Date()) - parsedDate) / 1000;
            var r = '';
            if  (delta < 60) {
              r = delta + " " + settings.localization.seconds;
            } else if (delta < 120) {
              r = settings.localization.minute;
            } else if (delta < (45 * 60)) {
              r = (parseInt(delta / 60, 10)).toString() + " " + settings.localization.minutes;
            } else if (delta < (90 * 60)) {
              r = settings.localization.hour;
            } else if (delta < (24 * 60 * 60)) {
              r = '' + (parseInt(delta / 3600, 10)).toString() + " " + settings.localization.hours;
            } else if (delta < (48 * 60 * 60)) {
              r = settings.localization.day;
            } else {
              r = (parseInt(delta / 86400, 10)).toString() + " " + settings.localization.days;
            }
            return r;
          },

          // Update the relative timestamps
          updateTimestamps: function () {
            var twitter = this;
            $(twitter.container).find('span.time').each(function () {
              var time_element = twitter.settings.timeLinks ? $(this).find('a') : $(this);
              time_element.html(twitter.relativeTime(this.timeStamp));
            });
          },
          
          apiURL: function () {
            var params = {};

            var protocol = (window.location.protocol === 'https:') ? 'https:' : 'http:';
            var baseURL  = 'api.twitter.com/1/';
            var endpoint = '';
            
            // Override for Twitter-compatible APIs like Status.net
            if (this.settings.service) {
              baseURL = this.settings.service + '/api/';
            }
            
            // Search mode
            if (this.settings.mode === 'search') {
              baseURL  = (this.settings.service) ? this.settings.service + '/api/' : 'search.twitter.com/';
              endpoint = 'search';
              params   = {
                q:        (this.query && this.query !== '') ? this.query : null,
                geocode:  this.settings.geocode,
                lang:     this.settings.lang,
                rpp:      (this.settings.rpp) ? this.settings.rpp : this.settings.limit
              };
              
            // User/home timeline mode
            } else if (this.settings.mode === 'user_timeline' || this.settings.mode === 'home_timeline') {
              endpoint = 'statuses/' + this.settings.mode + '/' + encodeURIComponent(this.query);
              params = {
                count:           this.settings.limit,
                include_rts:     (this.settings.mode === 'user_timeline' && this.settings.retweets) ? '1' : null,
                exclude_replies: (!this.settings.replies) ? '1' : null
              };

            // Favorites mode
            } else if (this.settings.mode === 'favorites') {
              endpoint = 'favorites';
              params = {
                id:       encodeURIComponent(this.query)
              };

            // List mode
            } else if (this.settings.mode === 'list') {
              endpoint = encodeURIComponent(this.query.user) + 
                         '/lists/' + 
                         encodeURIComponent(this.query.list) + 
                         '/statuses';
              params = {
                per_page: this.settings.limit
              };
            }

            // Construct the query string
            var queryString = [];
            for (var param in params) {
              if (params.hasOwnProperty(param) && typeof params[param] !== 'undefined' && params[param] !== null) {
                queryString[queryString.length] = param + '=' + encodeURIComponent(params[param]);
              }
            }
            queryString = queryString.join("&");

            // Return the full URL
            return protocol + '//' + baseURL + endpoint + '.json?' + queryString + '&callback=?';
          },
          
          // The different APIs will format the results slightly different,
          // so this method normalizes the tweet object.
          parseTweet: function (json) {
            var tweet = {
              id:         (json.id_str) ? json.id_str : json.id,
              text:       json.text,
              created_at: json.created_at
            };

            // Search/regular API differences
            if (this.settings.mode === 'search') {
              tweet = $.extend(tweet, {
                screen_name:       json.from_user,
                profile_image_url: json.profile_image_url
              });
            } else {
              tweet = $.extend(tweet, {
                screen_name:       json.user.screen_name,
                profile_image_url: json.user.profile_image_url,
                created_at:        json.created_at.replace(/^(\w+)\s(\w+)\s(\d+)(.*)(\s\d+)$/, "$1, $3 $2$5$4") // Fix for IE
              });
            }
            
            // Twitter/Status.net
            if (this.settings.service) {
              tweet = $.extend(tweet, {
                url:         'http://' + this.settings.service + '/notice/' + tweet.id,
                profile_url: 'http://' + this.settings.service + '/' + json.from_user
              });
              if (window.location.protocol === 'https:') {
                tweet.profile_image_url = tweet.profile_image_url.replace('http:', 'https:');
              }

            } else {
              tweet = $.extend(tweet, {
                url:         'http://twitter.com/#!/' + tweet.screen_name + '/status/' + tweet.id,
                profile_url: 'http://twitter.com/#!/' + tweet.screen_name
              });
              // Someday, Twitter will add HTTPS support to twimg.com, but until then
              // we have to rewrite the profile image urls to the old Amazon S3 urls.
              if (window.location.protocol === 'https:') {
                var matches = tweet.profile_image_url.match(/http[s]?:\/\/a[0-9]\.twimg\.com\/(\w+)\/(\w+)\/(.*?)\.(\w+)/i);
                if (matches) {
                  tweet.profile_image_url = "https://s3.amazonaws.com/twitter_production/" + matches[1] + "/" + matches[2] + "/" + matches[3] + "." + matches[4];
                } else {
                  // Failsafe, if profile image url does not match the pattern above
                  // then, at least, change the protocol to HTTPS.
                  // The image may not load, but at least the page stays secure.
                  tweet.profile_image_url = tweet.profile_image_url.replace('http:', 'https:');
                }
              }
            }
            
            return tweet;
          },
          
          // Parses the tweet body, linking URLs, #hashtags and @usernames.
          parseText: function (text) {
            // URLs
            text = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function (m) {
              return '<a href="' + m + '" rel="external">' + m + '</a>';
            });

            // Twitter
            if (!this.settings.service) {
              // @usernames
              text = text.replace(/@[A-Za-z0-9_]+/g, function (u) {
                return '<a href="http://twitter.com/#!/' + u.replace(/^@/, '') + '" rel="external">' + u + '</a>';
              });
              // #hashtags
              text = text.replace(/#[A-Za-z0-9_\-]+/g, function (u) {
                return '<a href="http://twitter.com/#!/search?q=' + u.replace(/^#/, '%23') + '" rel="external">' + u + '</a>';
              });
              
            // Other APIs
            } else {
              text = text.replace(/@[A-Za-z0-9_]+/g, function (u) {
                return '<a href="http://' + settings.service + '/' + u.replace(/^@/, '') + '" rel="external">' + u + '</a>';
              });
              text = text.replace(/#[A-Za-z0-9_\-]+/g, function (u) {
                return '<a href="http://' + settings.service + '/search/notice?q?' + u.replace(/^#/, '%23') + '" rel="external">' + u + '</a>';
              });
            }
            
            return text;
          },
          
          // Renders a tweet to HTML
          renderTweet: function (tweet) {
            var html = '<div class="tweet tweet-' + tweet.id + '">';

            if (this.settings.showAuthor) {
              html += '<img width="' + this.settings.imageSize + '" height="' + this.settings.imageSize + '" src="' + tweet.profile_image_url + '" />';
              html += '<p class="text"><span class="username"><a href="' + tweet.profile_url + '" rel="external">' + tweet.screen_name + '</a>:</span> ';
            } else {
              html += '<p class="text"> ';
            }

            html += this.parseText(tweet.text);
            
            if (this.settings.timeLinks) {
              html += ' <span class="time">';
              html += '<a href="' + tweet.url + '" rel="external">';
              html += this.relativeTime(tweet.created_at);
              html += '</a></span>';
            } else {
              html += ' <span class="time">' + this.relativeTime(tweet.created_at) + '</span>';
            }

            html += '</p></div>';

            return html;
          },

          // Handle reloading
          refresh: function (initialize) {
            var twitter = this;
            if (twitter.settings.refresh || initialize) {

              $.getJSON(twitter.apiURL(), function (json) {
                var newTweets = 0;

                // The search and regular APIs differ somewhat
                var results = (twitter.settings.mode === 'search') ? json.results : json;

                $(results).reverse().each(function () {
                  var tweet = twitter.parseTweet(this);
                  
                  // Check if tweets should be filtered
                  if (!twitter.settings.filter || twitter.settings.filter(this)) {
                    // Check if this is actually a new tweet
                    if (Date.parse(tweet.created_at) > twitter.lastTimeStamp) {

                      // Insert the HTML
                      $(twitter.container).prepend(twitter.renderTweet(tweet));

                      // Make a note of the timestamp on the first span
                      // so we can update it later.
                      $(twitter.container).find('span.time:first').each(function () {
                        this.timeStamp = tweet.created_at;
                      });

                      // Fade in new tweets unless this is the first load.
                      if (!initialize) {
                        $(twitter.container).find('.tweet-' + tweet.id).hide().fadeIn();
                      }

                      // Remember the last timestamp for the next refresh.
                      twitter.lastTimeStamp = Date.parse(tweet.created_at);

                      newTweets += 1;
                    }
                  }
                });

                // Did we get any new tweets?
                if (newTweets > 0) {
                  // Remove old entries exceeding the limit
                  $(twitter.container).find('div.tweet:gt(' + (twitter.settings.limit - 1) + ')').remove();

                  // Run callback
                  if (twitter.callback) {
                    twitter.callback(domNode, newTweets);
                  }

                  // Trigger event
                  $(domNode).trigger('tweets');
                }
              });
            }  
          },

          // Start refreshing
          start: function () {
            var twitter = this;
            if (!this.interval) {
              this.interval = setInterval(function () {
                twitter.refresh();
              }, twitter.settings.rate);
              this.refresh(true);
            }
          },

          // Stop refreshing
          stop: function () {
            if (this.interval) {
              clearInterval(this.interval);
              this.interval = false;
            }
          },

          // Clear all tweets
          clear: function () {
            $(this.container).find('div.tweet').remove();
            this.lastTimeStamp = null;
          }
        };

        var twitter = this.twitter;

        // Update the timestamps in realtime
        this.timeInterval = setInterval(function () {
          twitter.updateTimestamps();
        }, 5000);

        this.twitter.start();
      }
    });
    return this;
  };
})(jQuery);


// JavaScript Document
/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
	setup: function() {
		if ( this.addEventListener )
			for ( var i=types.length; i; )
				this.addEventListener( types[--i], handler, false );
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		if ( this.removeEventListener )
			for ( var i=types.length; i; )
				this.removeEventListener( types[--i], handler, false );
		else
			this.onmousewheel = null;
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});


function handler(event) {
	var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
	
	event = $.event.fix(event || window.event);
	event.type = "mousewheel";
	
	if ( event.wheelDelta ) delta = event.wheelDelta/120;
	if ( event.detail     ) delta = -event.detail/3;
	
	// Add events and delta to the front of the arguments
	args.unshift(event, delta);

	return $.event.handle.apply(this, args);
}

})(jQuery);

/**
 * @version		$Id:  $Revision
 * @package		jquery
 * @subpackage	lofslidernews
 * @copyright	Copyright (C) JAN 2010 LandOfCoder.com <@emai:landofcoder@gmail.com>. All rights reserved.
 * @website     http://landofcoder.com
 * @license		This plugin is dual-licensed under the GNU General Public License and the MIT License 
 */
// JavaScript Document
(function($) {
	 $.fn.lofJSidernews = function( settings ) {
	 	return this.each(function() {
			// get instance of the lofSiderNew.
			new  $.lofSidernews( this, settings ); 
		});
 	 }
	 $.lofSidernews = function( obj, settings ){
		this.settings = {
			direction	    	: '',
			mainItemSelector    : 'li',
			navInnerSelector	: 'ul',
			navSelector  		: 'li' ,
			navigatorEvent		: 'click',
			wapperSelector: 	'.lof-main-wapper',
			interval	  	 	: 4000,
			auto			    : true, // whether to automatic play the slideshow
			maxItemDisplay	 	: 3,
			startItem			: 0,
			navPosition			: 'vertical', 
			navigatorHeight		: 100,
			navigatorWidth		: 252,
			duration			: 600,
			navItemsSelector    : '.lof-navigator li',
			navOuterSelector    : '.lof-navigator-outer' ,
			isPreloaded			: true,
			easing				: 'easeInOutQuad'
		}	
		$.extend( this.settings, settings ||{} );	
		this.nextNo         = null;
		this.previousNo     = null;
		this.maxWidth  = this.settings.mainWidth || 717;
		this.wrapper = $( obj ).find( this.settings.wapperSelector );	
		this.slides = this.wrapper.find( this.settings.mainItemSelector );
		if( !this.wrapper.length || !this.slides.length ) return ;
		// set width of wapper
		if( this.settings.maxItemDisplay > this.slides.length ){
			this.settings.maxItemDisplay = this.slides.length;	
		}
		this.currentNo      = isNaN(this.settings.startItem)||this.settings.startItem > this.slides.length?0:this.settings.startItem;
		this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector );	
		this.navigatorItems = $( obj ).find( this.settings.navItemsSelector ) ;
		this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector );
		
		if( this.settings.navPosition == 'horizontal' ){ 
			this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth );
			this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth );
			this.navigatorOuter.height(	this.settings.navigatorHeight );
			
		} else {
			this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight );	
			
			this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight );
			this.navigatorOuter.width(	this.settings.navigatorWidth );
		}		
		this.navigratorStep = this.__getPositionMode( this.settings.navPosition );		
		this.directionMode = this.__getDirectionMode();  
		
		
		if( this.settings.direction == 'opacity') {
			this.wrapper.addClass( 'lof-opacity' );
			$(this.slides).css('opacity',0).eq(this.currentNo).css('opacity',1);
		} else { 
			this.wrapper.css({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } );
		}

		
		if( this.settings.isPreloaded ) {
			this.preLoadImage( this.onComplete );
		} else {
			this.onComplete();
		}
		
	 }
     $.lofSidernews.fn =  $.lofSidernews.prototype;
     $.lofSidernews.fn.extend =  $.lofSidernews.extend = $.extend;
	 
	 $.lofSidernews.fn.extend({
							  
		startUp:function( obj, wrapper ) {
			seft = this;

			this.navigatorItems.each( function(index, item ){
				$(item).click( function(){
					seft.jumping( index, true );
					seft.setNavActive( index, item );					
				} );
				$(item).css( {'height': seft.settings.navigatorHeight, 'width':  seft.settings.navigatorWidth} );
			})
			this.registerWheelHandler( this.navigatorOuter, this );
			this.setNavActive(this.currentNo );
			
			if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){
				this.registerButtonsControl( 'click', this.settings.buttons, this );

			}
			if( this.settings.auto ) 
			this.play( this.settings.interval,'next', true );
			
			return this;
		},
		onComplete:function(){
			setTimeout( function(){ $('.preload').fadeOut( 900 ); }, 400 );	this.startUp( );
		},
		preLoadImage:function(  callback ){
			var self = this;
			var images = this.wrapper.find( 'img' );
	
			var count = 0;
			images.each( function(index,image){ 
				if( !image.complete ){				  
					image.onload =function(){
						count++;
						if( count >= images.length ){
							self.onComplete();
						}
					}
					image.onerror =function(){ 
						count++;
						if( count >= images.length ){
							self.onComplete();
						}	
					}
				}else {
					count++;
					if( count >= images.length ){
						self.onComplete();
					}	
				}
			} );
		},
		navivationAnimate:function( currentIndex ) { 
			if (currentIndex <= this.settings.startItem 
				|| currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) {
					this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2;
					if (this.settings.startItem < 0) this.settings.startItem = 0;
					if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) {
						this.settings.startItem = this.slides.length-this.settings.maxItemDisplay;
					}
			}		
			this.navigatorInner.stop().animate( eval('({'+this.navigratorStep[0]+':-'+this.settings.startItem*this.navigratorStep[1]+'})'), 
												{duration:500, easing:'easeInOutQuad'} );	
		},
		setNavActive:function( index, item ){
			if( (this.navigatorItems) ){ 
				this.navigatorItems.removeClass( 'active' );
				$(this.navigatorItems.get(index)).addClass( 'active' );	
				this.navivationAnimate( this.currentNo );	
			}
		},
		__getPositionMode:function( position ){
			if(	position  == 'horizontal' ){
				return ['left', this.settings.navigatorWidth];
			}
			return ['top', this.settings.navigatorHeight];
		},
		__getDirectionMode:function(){
			switch( this.settings.direction ){
				case 'opacity': this.maxSize=0; return ['opacity','opacity'];
				default: this.maxSize=this.maxWidth; return ['left','width'];
			}
		},
		registerWheelHandler:function( element, obj ){ 
			 element.bind('mousewheel', function(event, delta ) {
				var dir = delta > 0 ? 'Up' : 'Down',
					vel = Math.abs(delta);
				if( delta > 0 ){
					obj.previous( true );
				} else {
					obj.next( true );
				}
				return false;
			});
		},
		registerButtonsControl:function( eventHandler, objects, self ){ 
			for( var action in objects ){ 
				switch (action.toString() ){
					case 'next':
						objects[action].click( function() { self.next( true) } );
						break;
					case 'previous':
						objects[action].click( function() { self.previous( true) } );
						break;
				}
			}
			return this;	
		},
		onProcessing:function( manual, start, end ){	 		
			this.previousNo = this.currentNo + (this.currentNo>0 ? -1 : this.slides.length-1);
			this.nextNo 	= this.currentNo + (this.currentNo < this.slides.length-1 ? 1 : 1- this.slides.length);				
			return this;
		},
		finishFx:function( manual ){
			if( manual ) this.stop();
			if( manual && this.settings.auto ){ 
				this.play( this.settings.interval,'next', true );
			}		
			this.setNavActive( this.currentNo );	
		},
		getObjectDirection:function( start, end ){
			return eval("({'"+this.directionMode[0]+"':-"+(this.currentNo*start)+"})");	
		},
		fxStart:function( index, obj, currentObj ){
				if( this.settings.direction == 'opacity' ) { 
					$(this.slides).stop().animate({opacity:0}, {duration: this.settings.duration, easing:this.settings.easing} );
					$(this.slides).eq(index).stop().animate( {opacity:1}, {duration: this.settings.duration, easing:this.settings.easing} );
				}else {
					this.wrapper.stop().animate( obj, {duration: this.settings.duration, easing:this.settings.easing} );
				}
			return this;
		},
		jumping:function( no, manual ){
			this.stop(); 
			if( this.currentNo == no ) return;		
			 var obj = eval("({'"+this.directionMode[0]+"':-"+(this.maxSize*no)+"})");
			this.onProcessing( null, manual, 0, this.maxSize )
				.fxStart( no, obj, this )
				.finishFx( manual );	
				this.currentNo  = no;
		},
		next:function( manual , item){

			this.currentNo += (this.currentNo < this.slides.length-1) ? 1 : (1 - this.slides.length);	
			this.onProcessing( item, manual, 0, this.maxSize )
				.fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this )
				.finishFx( manual );
		},
		previous:function( manual, item ){
			this.currentNo += this.currentNo > 0 ? -1 : this.slides.length - 1;
			this.onProcessing( item, manual )
				.fxStart( this.currentNo, this.getObjectDirection(this.maxSize ), this )
				.finishFx( manual	);			
		},
		play:function( delay, direction, wait ){	
			this.stop(); 
			if(!wait){ this[direction](false); }
			var self  = this;
			this.isRun = setTimeout(function() { self[direction](true); }, delay);
		},
		stop:function(){ 
			if (this.isRun == null) return;
			clearTimeout(this.isRun);
            this.isRun = null; 
		}
	})
})(jQuery)


