(function($$, $){
  $$.extend = function (destination, source, callback) {
                for (var property in source)
                  destination[property] = source[property];
                if($$.dev) destination['__noSuchMethod__'] = function (prop, args){ error(prop, " : no such method exists", args); };
                if ($.isFunction(callback)) callback();
                return destination;
  };
  $$.colors = [   "#000000", "#444444", "#666666", "#999999", "#CCCCCC", "#EEEEEE", "#F3F3F3", "#FFFFFF", 
                  "#FF0000", "#FF9900", "#FFFF00", "#00FF00", "#00FFFF", "#0000FF", "#9900FF", "#FF00FF", 
                  "#FFCCCC", "#FCE5CD", "#FFF2CC", "#D9EAD3", "#D0E0E3", "#CFE2F3", "#D9D2E9", "#EAD1DC", 
                  "#EA9999", "#F9CB9C", "#FFE599", "#B6D7A8", "#A2C4C9", "#9FC5E8", "#B4A7D6", "#D5A6BD", 
                  "#E06666", "#F6B26B", "#FFD966", "#93C47D", "#76A5AF", "#6FA8DC", "#8E7CC3", "#C27BA0", 
                  "#CC0000", "#E69138", "#F1C232", "#6AA84F", "#45818E", "#3D85C6", "#674EA7", "#A64D79", 
                  "#990000", "#B45F06", "#BF9000", "#38761D", "#134F5C", "#0B5394", "#351C75", "#741B47", 
                  "#660000", "#783F04", "#7F6000", "#274E13", "#0C343D", "#073763", "#20124D", "#4C1130" ];
  $$.cache = {};
  $$.extend(window, {
    log: ($$.dev && window.console) ? function() { console.log.apply(console, arguments); } : function() { },
    error: ($$.dev && window.console) ? function() { console.error.apply(console, arguments); } : function() { },
    dir: ($$.dev && window.console) ? function(a) { console.dir(a); } : function() { },
    info: ($$.dev && window.console) ? function(a) { console.info(a); } : function() { },
    toggle_language: function(display_languagebar, select_language) {
      if (display_languagebar == true) {
        $('#general_bar_1,#general_bar_2').toggle();
        if(select_language!="") {
          $("#language_selected_map").val() = select_language;
        }
      } else {
        $('#general_bar_1,#general_bar_2').toggle();
      }
    },
    cookie: function(name, value, options) {/*view http://plugins.jquery.com/files/jquery.cookie.js.txt here we directly append this to window object instead of jQuery */
        if (typeof value != 'undefined') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString();
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },
    getUrlVars: function(url){
      url = url ? url : window.location.href;
      var vars = [], hash;
      var hashes = url.slice(url.indexOf('?') + 1).split('&');
      for(var i = 0; i < hashes.length; i++)
      {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
      return vars;
    },
    getUrlVar: function(name,url){
      return this.getUrlVars(url)[name];
    }
  }, function(){
    log("logging enabled");
    log("Window object extended");
  });
  
  $$.extend(Math, {
    uuid : (function() { /* Taken from http://www.broofa.com/Tools/Math.uuid.js */
      var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); 
      return function (len, radix) {
        var chars = CHARS, uuid = [];
        radix = radix || chars.length;
        if (len) {
          for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
        } else {
          var r;
          uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
          uuid[14] = '4';
          for (var i = 0; i < 36; i++) {
            if (!uuid[i]) {
              r = 0 | Math.random()*16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
          }
        }
        return uuid.join('');
      };
    })()
  });
  
  $$.extend(String.prototype, {
	 	JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,
		ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
		specialChar: {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'\\': '\\\\'
		},
		blank: function(s) {
			return /^\s*$/.test(this.s(s) || ' ');
		},
		capitalize: function(s) {
			s = this.s(s);
			s = s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
			return this.r(arguments,0,s);
		},
		empty: function(s) {
			return this.s(s) === '';
		},
		escapeHTML: function(s) {
			s = this.s(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/,'&quot;');
			return this.r(arguments,0,s);
		},
		evalScripts: function(s) {
			var scriptTags = this.extractScripts(this.s(s)), results = [];
			if (scriptTags.length > 0) {
				for (var i = 0; i < scriptTags.length; i++) {
					results.push(eval(scriptTags[i]));
				}
			}
			return results;
		},
		extractScripts: function(s) {
			var matchAll = new RegExp(this.ScriptFragment, 'img'), matchOne = new RegExp(this.ScriptFragment, 'im'), scriptMatches = this.s(s).match(matchAll) || [], scriptTags = [];
			if (scriptMatches.length > 0) {
				for (var i = 0; i < scriptMatches.length; i++) {
					scriptTags.push(scriptMatches[i].match(matchOne)[1] || '');
				}
			}
			return scriptTags;
		},
		gsub: function(pattern, replacement, s) {
			s = this.s(s);
			if ($.isFunction(replacement)) { s = this.sub(pattern, replacement, -1, s); }
			else { s = s.split(pattern).join(replacement); }
			return this.r(arguments,2,s);
		},
		include: function(pattern, s) {
			return this.s(s).indexOf(pattern) > -1;
		},
		interpolate: function(obj, pattern, s) {
			s = this.s(s);
			if (!pattern) { pattern = /(\#\{\s*(\w+)\s*\})/; }
			var gpattern = new RegExp(pattern.source, "g");
			var matches = s.match(gpattern), i;
			for (i=0; i<matches.length; i++) {
				s = s.replace(matches[i], obj[matches[i].match(pattern)[2]].toString().escapeHTML());
			}
			return this.r(arguments,2,s);
		},
		scan: function(pattern, replacement, s) {
			s = this.s(s);
			this.sub(pattern, replacement, -1, s);
			return this.r(arguments,2,s);
		},
		startsWith: function(pattern, s) {
			return this.s(s).indexOf(pattern) === 0;
		},
		strip: function(s) {
			s = $.trim(this.s(s));
			return this.r(arguments,0,s);
		},
		stripScripts: function(s) {
			s = this.s(s).replace(new RegExp(this.ScriptFragment, 'img'), '');
			return this.r(arguments,0,s);
		},
		stripTags: function(s) {
			s = this.s(s).replace(/<\/?[^>]+>/gi, '');
			return this.r(arguments,0,s);
		},
		sub: function(pattern, replacement, count, s) {
			s = this.s(s);
			if (pattern.source && !pattern.global) {
				var patternMods = (pattern.ignoreCase)?"ig":"g";
				patternMods += (pattern.multiline)?"m":"";
				pattern = new RegExp(pattern.source, patternMods);
			}
			var sarray = s.split(pattern), matches = s.match(pattern);
			if ($.browser.msie) {
				if (s.indexOf(matches[0]) == 0) sarray.unshift("");
				if (s.lastIndexOf(matches[matches.length-1]) == s.length - matches[matches.length-1].length) sarray.push("");
			}
			count = (count < 0)?(sarray.length-1):count || 1;
			s = sarray[0];
			for (var i=1; i<sarray.length; i++) {
				if (i <= count) {
					if ($.isFunction(replacement)) {
						s += replacement(matches[i-1] || matches) + sarray[i];
					} else { s += replacement + sarray[i]; }
				} else { s += (matches[i-1] || matches) + sarray[i]; }
			}
			return this.r(arguments,3,s);
		},
		truncate: function(length, truncation, s) {
			s = this.s(s);
			length = length || 30;
			truncation = (!truncation) ? '...' : truncation;
			s = (s.length > length) ? s.slice(0, length - truncation.length) + truncation : String(s);
			return this.r(arguments,2,s);
		},
		unescapeHTML: function(s) {
			s = this.stripTags(this.s(s)).replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/,'"');
			return this.r(arguments,0,s);
		},
		r: function(args, size, s) {
			if (args.length > size || this.str === undefined) {
				return s;
			} else {
				this.str = ''+s;
				return this;
			};
		},
		s: function(s) {
			if (s === '' || s) { return s; }
			if (this.str === '' || this.str) { return this.str; }
			return this;
		},
		chop: function(){
		  return this.slice(0, this.length - 1)
		}
	}, function (){
	  log("String object extended");
	});
  $$.extend(Array.prototype, {
    empty: function(){
      return (this.length < 1);
    }
  });
  $$.extend($$, {
    createElement: function(type, prop){
      var element = document.createElement(type);
      for (i in prop)
        element.setAttribute(i, prop[i]);
      return element;
    },
    tooltip: function (message,element_id){
      $('#'+element_id).hover(function(e) {
        var element = $(e.currentTarget),
            position = element.position();
        $$.cache.toolTip = element.append("<div class='tooltip' style='top:"+position.top+"px;left:"+position.left+"px;z-index:9999999;'>"+message+"</div>").children('.tooltip');
      }, function() {
        $$.cache.toolTip.remove();
        delete $$.cache.toolTip;
      });
    },
    addRedirectURLForLogin: function (){
      $('a[href=/login]').attr('href','/login?from_source='+encodeURIComponent(window.location.pathname));
    },
    alert: function(message, customTitle){
      customTitle = customTitle || "Alert!";
      $('body').append('<div id="dialog" class="ui-state-error ui-corner-all" title="'+customTitle+'" style="display:none;">\
                        <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'+message+'</p></div>');
      $("#dialog").dialog({
      			bgiframe: false,
      			modal: false,
      			closeOnEscape: true,
      			close: function(){
      			  $('#dialog').remove();
      			},
      			buttons: {
      				Ok: function() {
      					$('#dialog').remove();
      				}
      			}
      		});
    },
    confirm: function(title,message,callback, falseCallBack, height, width){
      if(title == null) title = "Confirm";
      if(message == null) message = "Are you sure want to proceed ?";
      $('body').append('<div id="dialog" style="display:none;" title="'+title+'">\
                        <p><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 20px 0;"></span>'+message+'</p></div>');
      $("#dialog").dialog({
      			bgiframe: true,
      			resizable: false,
      			height: height,
      			width: width,
      			modal: false,
      			overlay: {
      				backgroundColor: '#000',
      				opacity: 0.5
      			},
      			closeOnEscape: true,
      			dialogClass: 'confirm',
      			close: function(){
      			  $(this).dialog('destroy');
      			  $('#dialog').remove();
      			},
      			buttons: {
      				'Ok': function() {
      					$(this).dialog('destroy');
      					$('#dialog').remove();
      					if ($.isFunction(callback)) callback();
      					return true;
      				},
      				'Cancel': function() {
      					$(this).dialog('destroy');
      					$('#dialog').remove();
      					if ($.isFunction(falseCallBack)) falseCallBack();
      					return false;
      				}
      			}
      		});
    },
    prompt: function(title,message,default_value,callback, optional_message){
      optional_message = optional_message || "";
      if (title == null || message == null || callback == null)
        return false;
      default_value = default_value || "";
      $('body').append('<div id="dialog" style="display:none;" title="'+title+'"><label for="prompt_value">'+message+'</label>&nbsp;&nbsp;\
                        <input type="text" id="prompt_value" value="'+default_value+'"/><br><br><span>'+optional_message+'</span></div>');
      if (optional_message.blank()) optional_message = null;
      $("#dialog").dialog({
      			bgiframe: true,
      			resizable: false,
      			height: optional_message == null ? 300 : 180,
      			width: optional_message == null ? 300 : 500,
      			modal: false,
      			overlay: {
      				backgroundColor: '#000',
      				opacity: 0.5
      			},
      			closeOnEscape: true,
      			dialogClass: 'confirm',
      			close: function(){
      			  $(this).dialog('destroy');
      			  $('#dialog').remove();
      			},
      			buttons: {
      				'Ok': function() {
      				  var value = $('#prompt_value').val();
      					$(this).dialog('destroy');
      					$('#dialog').remove();
      					if ($.isFunction(callback)) callback(value);
      					return true;
      				},
      				'Close': function() {
      					$(this).dialog('destroy');
      					$('#dialog').remove();
      					return false;
      				}
      			}
      		});
    },
    dropDown: function(hoverTargetId,dropDownId){
      $(hoverTargetId).hover(function() {
        $(dropDownId).show();
      }, function() {
        $(dropDownId).hide();
      });
    },
    makeExternalLinksOpenInNewTab: function(){
      $('a[hostname!='+window.location.hostname+']').attr('target','_blank');
    },
    ga: function(tag, type, optional_label, optional_value){
      if(type.match(/pageload/)){ 
        $$.cache['pageTag'] = type; 
      }
      $(function(){
        log([new Date(),"Event tracking",tag,type,window.pageTracker._trackEvent(tag, type, optional_label, optional_value)]);
      });
    },
    flashNoticeClose: function(){
      $("#page-error .closeThis, #page-success .closeThis, #page-notice .closeThis, #page-warning .closeThis, #page-message .closeThis, .information .closeThis").live( "click", function (e) {
          $(e.target).parent().hide();
          return false;
        });
    },
    handleSearchFields: function(){
      $('.headerSearch input.text').focus(function() {
        if ($(this).val() == 'Search'){
          $(this).val('');
        }
      });
      $('.headerSearch input.text').blur(function() {
        $(this).val($.trim($(this).val()));
        if ($(this).val() == ''){
          $(this).val('Search');
        }
      });
      $('.headerSearch').submit(function(event) {
        var searchField = $(this).find('input.text');
        searchField.val($.trim(searchField.val()));
        if (searchField.val() == 'Search' || searchField.val() == ''){
          event.preventDefault();
          searchField.focus();
        }
      });
    },
    colorEntered: function(){
      $('.color_picker').each(function(i,j){
        var element =  $(j);
        element.children('div').css('background-color',element.siblings('input').val());
      });
    },
    colorPicker: function(){
      $$.colorString = '<div style="top: #{top}px; left: #{left}px;" class="picker">';
      for(i in $$.colors)
        $$.colorString += '<div onclick="slideshare_object.colorPicked(this);"\
                            style="margin: 2px; float: left; width: 12px; height: 12px; background-color: '+$$.colors[i]+' ; cursor: pointer;">\
                            &nbsp;</div>';
      $$.colorString += '</div>';
      $$.colorEntered();
      $('.color_hex').blur(function(e) {
        var element = $(e.target);
        element.siblings('div.color_picker').children().css('background-color', element.val());
      });
      $('.color_picker div').click(function(e) {
        var element = $(e.target),
            position = element.position(),
            parent = element.parent().parent();
        if(parent.children().length == 3){
          $('.picker').remove();
          parent.append(slideshare_object.colorString.interpolate({top: position.top, left: position.left - 146}));
        }
        else
          parent.children(':last').remove();
      });
    },
    colorPicked: function(e){
      var element = $(e),
          parent = element.parent(),
          color = slideshare_object.rgb2hex(element.css('background-color'));
      parent.siblings('div.color_picker').children().css('background-color', color).end().siblings('input').val(color);
      parent.remove();
    },
    rgb2hex: function(str){
      if ($.browser.msie) {
        return str.toUpperCase();
      }else{
        var parts = str.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        delete (parts[0]);
        for (var i = 1; i <= 3; ++i) {
            parts[i] = parseInt(parts[i]).toString(16);
            if (parts[i].length == 1) parts[i] = '0' + parts[i];
        }
        return '#'+parts.join('').toUpperCase();
      }
    },
    tabs: function(id){
      $(id).find(':first li a').click(function(e) {
        var element = $(e.target);
        $(id).children(':not(:first)').hide();
        element.parent().attr('class','ui-tabs-selected').siblings().removeAttr('class');
        $(e.target.hash).show();
        $('#redirect').val(e.target.hash);
        return false;
      }).end().children(':not(:first)').hide().end().find(':first li a:first').click();
    },
    checkGlobals: function() {
      try{
        if($$.dontCheckGlobals) return true;
        if ( console.groupCollapsed ) console.groupCollapsed( "ss inits" );
        info("Globals objects used");
        var a = {},b = [],d = document,e = 'addEventListener,document,location,navigator,window'.split(','),f,i = e.length,w = window,g = {},f = d.createElement('iframe');
        for (v in w) a[v] = { 'type': typeof w[v],'val': w[v] };
        f.style.display = 'none';
        d.body.appendChild(f);
        f.src = 'about:blank';
        f = f.contentWindow || f.contentDocument;
        for (v in a) if (typeof f[v] != 'undefined') delete a[v];
        while (--i) delete a[e[i]];
        dir(a);
        if ( console.groupEnd ) console.groupEnd( "ss inits" );
      }catch(e){}
    },
    showPopup: function (url) {
      var w=660, h=490, Xpos=((screen.availWidth - w)/2),Ypos=((screen.availHeight - h)/2);
      window.open( url, 'ss_share', 'width=' + w + ',height=' + h + ',toolbar=no,resizable=fixed,status=no,scrollbars=no,menubar=no,screenX=' + Xpos+',screenY='+Ypos ).focus();
    },
    dimLight: {
      init: function (options) {
        $$.cache.dimLight = {};
        $$.cache.currentDimLight = options.name;
        $$.cache.dimLight[options.name] = {
          'url': options.url,
          'type': options.type,
          'datatype': options.datatype,
          'data': options.data,
          'callback': options.callback,
          'backoff': options.backoff,
          'defaultBackoff': options.backoff
        }
        $$.cache.dimLight[$$.cache.currentDimLight]['start'] = true;
        $$.dimLight.send();
      },
      send: function () {
        if($$.cache.dimLight[$$.cache.currentDimLight]['start']){
          $$.cache.dimLight[$$.cache.currentDimLight]['start'] = false;
          $.ajax({
            url: $$.cache.dimLight[$$.cache.currentDimLight].url,
            type: $$.cache.dimLight[$$.cache.currentDimLight].type,
            dataType: $$.cache.dimLight[$$.cache.currentDimLight].datatype,
            data: {'ids' : $$.cache.dimLight[$$.cache.currentDimLight].data},
            beforeSend: function(){
              info("Dimlight call triggered for "+$$.cache.currentDimLight+" at "+Date());
            },
            success: function(data) {
              info("Dimlight success for "+$$.cache.currentDimLight+" at "+Date());
              $$.cache.dimLight[$$.cache.currentDimLight]['start'] = true;
              if($.isFunction($$.cache.dimLight[$$.cache.currentDimLight].callback))$$.cache.dimLight[$$.cache.currentDimLight].callback(data);
              window.setTimeout( $$.dimLight.send, $$.cache.dimLight[$$.cache.currentDimLight].defaultBackoff );
            },
            error: function() {
              info("Dimlight error for "+$$.cache.currentDimLight+" at "+Date());
              error(arguments);
              window.setTimeout( $$.dimLight.send, $$.cache.dimLight[$$.cache.currentDimLight].backoff );
              $$.cache.dimLight[$$.cache.currentDimLight]['start'] = true;
              $$.cache.dimLight[$$.cache.currentDimLight].backoff += $$.cache.dimLight[$$.cache.currentDimLight].backoff * 0.3
            }
          });
        }
      },
      stop: function () {
        while($$.cache.dimLight[$$.cache.currentDimLight]['start']){
          info("Stopping Dimlight...");
          $$.cache.dimLight[$$.cache.currentDimLight]['start'] = false;
          info("Stopped Dimlight...")
        }
        return !$$.cache.dimLight[$$.cache.currentDimLight]['start'];
      }
    },
    scrollTo: function (id) {
      var $target = $(id);
      if ($target.length) {
        $('html,body').animate({scrollTop: $target.offset().top - 100}, 1000);
        $target.focus();
      }
    },
    tagTextBoxInteraction: function (elem) {
      $.each(elem, function(i,j){
        if (j.value.blank()) {
          j.value = 'separate tags by comma';
          $(j).attr("style","color:#777");
        };
        $(j).focus(function(){
          if (this.value == 'separate tags by comma') { this.value = ""; $(j).attr("style","color:#333"); };
        }).blur(function () {
          if (this.value.blank()) { this.value = "separate tags by comma"; $(j).attr("style","color:#777"); };
        });
      });
    },
    initTagTextBox: function () {
      var elem = $('.action-tags-text-input');
      $$.tagTextBoxInteraction(elem);
    },
    getStyle: function(url){
      $.get(url, function(data){
        $('head').append("<style>"+data+"</style>");
      });
    }
  }, function (){
    log("$$ object extended");
  });
  $$.extend($.fn, {
    konami: function(callback, code) {
      if(code == undefined) code = "38,38,40,40,37,39,37,39,66,65";
      return this.each(function() {
        var kkeys = [];
        $(this).keydown(function(e){
          kkeys.push( e.keyCode );
          if ( kkeys.toString().indexOf( code ) >= 0 ){
            $(this).unbind('keydown', arguments.callee);
            callback(e);
          }
        }, true);
      });
    },
    toggleText: function(){
      this.each(function(i, j) {
        j = $(j);
        j.data('text_to_toggle', j.val());
        tc = j.attr('class').match(/(quietest|quieter|quiet)/);
        tc = tc ? tc.join(' ') : '';
        j.data('quiet_class', tc);
        j.focus(function() {
          var e = $(this);
          if (e.val() == e.data('text_to_toggle')) {
            e.val("").removeClass(j.data('quiet_class'));
          };
        }).blur(function() {
          var e = $(this);
          if (e.val().length < 1) {
            e.val(e.data('text_to_toggle')).addClass(j.data('quiet_class'));
          };
        });
      }); 
    },
    fixPNG: function(){
      return this.each(function () {
        var image = $(this).css('backgroundImage');
        if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
          image = RegExp.$1;
          $(this).css({
            'backgroundImage': 'none',
            'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + ($(this).css('backgroundRepeat') == 'no-repeat' ? 'crop' : 'scale') + ", src='" + image + "')"
          }).each(function () {
            var position = $(this).css('position');
            if (position != 'absolute' && position != 'relative') $(this).css('position', 'relative');
          });
        }
      });
    }
  }, function (){
    log("$.fn object extended");
  });
  
  
  $$.extend($$, {
    autosuggest_top: function() {
      $(".searchSuggestionsTop li").live("click", function() {
        $("#search_query_top").val($(this).html());
        $(".searchSuggestionsTop").remove();
      });
      $(".searchSuggestionsTop li").live("mousemove", function(){
        $("#search_query_top").val($(this).html());
        $(this).attr("class", "searchHighlight");
      });
      $(".searchSuggestionsTop li").live("mouseout", function(){
        $(this).removeAttr("class");
      });
      $(".searchSuggestionsTop").live("mouseover", function(){
        /* Remove any initial suggestions from keyboard
        when the mouse pointer is moved inside suggestion box */
        var temp = $(".searchSuggestionsTop li.searchHighlight");
        if (!(temp.length == 0)) {
          temp.removeAttr("class");
        }
      });
      $("#search_query_top").blur(function() { 
        $(".searchSuggestionsTop").hide();
      });
      $("#search_query_top").focus(function() {
        $(".searchSuggestionsTop").show();
      });
      var delay = (function(){
        var timer = 0;
        return function(callback, ms){
          clearTimeout (timer);
          timer = setTimeout(callback, ms);
        };
      })();
      $("#search_query_top").keyup(function(event) {
      delay(function() {
        var flag = 0;  
        if (parseInt(event.keyCode) == 40) {
          /* Down key */
          /* Remove any previous suggestions (from mouse) */
          var current_suggestion = $(".searchSuggestionsTop li.searchHighlight");
          if (current_suggestion[0] == $(".searchSuggestionsTop li:hover")[0]) {
            $(".searchSuggestionsTop li:hover").removeAttr("class");
            $(".searchSuggestionsTop").mouseout(); // :P
          }
          if (current_suggestion.length == 0) {
            /* No current suggestion
            * Go to the first suggestion */
            var suggestion = $(".searchSuggestionsTop li:first");
            suggestion.attr("class", "searchHighlight");
            $("#search_query_top").val(suggestion.html());
          }
          else if (current_suggestion[0] == $(".searchSuggestionsTop li:last")[0]) {
            /* Last suggestion selected
            * Go back to the first suggestion */
            var suggestion = $(".searchSuggestionsTop li:first");
            suggestion.attr("class", "searchHighlight");
            $(".searchSuggestionsTop li:last").removeAttr("class");
            $("#search_query_top").val(suggestion.html());
          }
          else {
            var new_suggestion = current_suggestion.next();
            $("#search_query_top").val(new_suggestion.html());
            current_suggestion.removeAttr("class");
            new_suggestion.attr("class", "searchHighlight");
          }
          flag = 1;
        }
        if (parseInt(event.keyCode) == 38) {
          /* Up key */
          /* Remove any previous suggestions (from mouse) */
          var current_suggestion = $(".searchSuggestionsTop li.searchHighlight");
          if (current_suggestion[0] == $(".searchSuggestionsTop li:hover")[0]) {
            $(".searchSuggestionsTop li:hover").removeAttr("class");
            $(".searchSuggestionsTop").mouseout(); // :P
          }
          if (current_suggestion.length == 0) {
            /* No current suggestion
            * Go to the last suggestion */
            var suggestion = $(".searchSuggestionsTop li:last");
            suggestion.attr("class", "searchHighlight");
            $("#search_query_top").val(suggestion.html());
          }
          else if (current_suggestion[0] == $(".searchSuggestionsTop li:first")[0]) {
            /* First suggestion selected
            Go back to the last suggestion*/
            var suggestion = $(".searchSuggestionsTop li:last");
            suggestion.attr("class", "searchHighlight");
            $(".searchSuggestionsTop li:first").removeAttr("class");
            $("#search_query_top").val(suggestion.html());
          }
          else {
            var new_suggestion = current_suggestion.prev();
            $("#search_query_top").val(new_suggestion.html());
            current_suggestion.removeAttr("class");
            new_suggestion.attr("class", "searchHighlight");
          }
          flag = 1;
        }
        
        if (flag == 1) {
          return;
        }

        new_auto_suggest_query = $("#search_query_top").val();
        new_auto_suggest_query = new_auto_suggest_query.replace(/['"*&]/gi,'').replace(/\s{2,}/g,' ');
        new_auto_suggest_query = $.trim(new_auto_suggest_query);
        new_auto_suggest_query = new_auto_suggest_query.replace(/ /g,'?');
        new_auto_suggest_query = new_auto_suggest_query + "*";
        new_auto_suggest_query = new_auto_suggest_query + "&rows=8&wt=json&json.wrf=?";
        if (new_auto_suggest_query.length > 2) {
          $.getJSON("http://autosuggest.slideshare.net/?q=" + new_auto_suggest_query, function(data) {
            if (data.response.docs.length > 0) {
              $(".searchSuggestionsTop").remove();
              $("<ul class='searchSuggestionsTop'></ul>").insertAfter("#search_query_top");
              $.each(data.response.docs, function(i, item) {
                $("<li>" + item.raw_query + "</li>").appendTo(".searchSuggestionsTop");
              });
            }
            else {
              $(".searchSuggestionsTop").remove();
            }
          });
        }
      }, 50);
      });
    }
  }, function() {
    log("$$ extended");
  });
  
  
  $(document).ready(function() {
    /* All non-GET requests will add the authenticity token
       if not already present in the data packet */
    $("body").bind("ajaxSend", function(elm, xhr, s) {
      if (s.type == "GET") return;
      if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
      if (s.data) {
        s.data = s.data + "&";
      } else {
        s.data = "";
        /* if there was no data, $ didn't set the content-type */
        xhr.setRequestHeader("Content-Type", s.contentType);
      }
      s.data = s.data + encodeURIComponent(window._auth_token_name)
                      + "=" + encodeURIComponent(window._auth_token);
    });
    /*$$.makeExternalLinksOpenInNewTab(jQuery);*/
    $$.addRedirectURLForLogin();
    $$.flashNoticeClose();
    $$.handleSearchFields();
    $$.initTagTextBox();
    $('.toggle_text').toggleText();
    if($$.dev) $$.checkGlobals();
    $$.autosuggest_top();
    
  });
})(slideshare_object, jQuery);