var defaultKeywords = 'Type your keyword here...';

function positionLeftBox() {
  var centerY = parseInt($('#center').offset().top - 70);
  var $leftBox = $('#left');
  var scrollY = $(window).scrollTop();
  var fixedLeft = $leftBox.css('position') != 'relative';

  if ( scrollY > centerY && !fixedLeft ) {
    $leftBox.stop().css({
      position: 'fixed',
      top: 70,
      left: 5,
      margin: 0
    });
  } else if ( scrollY < centerY && fixedLeft ) {
    $leftBox.stop().css({
      position: 'relative',
      right: 150,
      top: 'auto',
      bottom: 'auto',
      left: 'auto',
      marginLeft: '-100%'
    });
  }
}

function getWindowHeight() {
  var windowHeight = 0;
  if (typeof(window.innerHeight) == 'number') {
    windowHeight = window.innerHeight;
  }
  else {
    if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    }
    else {
      if (document.body && document.body.clientHeight) {
        windowHeight = document.body.clientHeight;
      }
    }
  }
  return windowHeight;
}

function centerizeSearch() {
  if ($('.middle').exists()) {
    var windowHeight = getWindowHeight();
    if (windowHeight > 0) {
      var contentElement = document.getElementById('searchbox');
      var contentHeight = contentElement.offsetHeight;
      if (windowHeight - contentHeight > 0) {
        contentElement.style.position = 'relative';
        contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2) - 25) + 'px';
      }
      else {
        contentElement.style.position = 'static';
      }
    }
  }
}

function searchOrRedirect(url, q, t) {    
  
  if (q) {  
    $('#t').attr('value', t); 
    setTimeout(function() {
      $('#searchdo').append('<input id="sbi2" type="hidden" name="q" value="' + escape(q) + '" />');
      $('#searchdo').submit();
    }, 0);        
  } else {   
    setTimeout(function() {
      document.location = url + '?t=' + t;
    }, 0);    
  }
}

function moveSearchPosition(){
  setTimeout(function() {
    $('#search-box-position').submit();
  }, 0);
}

function changeShowLinks(){
  setTimeout(function() {
    $('#fav-site-form').submit();
  }, 0);
}

function changeSearchBarSize(){
  setTimeout(function() {
    $('#search-bar-form').submit();
  }, 0);
}

function removeAnchor(){
  var url = document.location.toString();
  var anchor_index = url.indexOf('#');
  if (anchor_index != -1) {
    url = url.substring(0, anchor_index);
  }
  setTimeout(function() {
    document.location = url;
  }, 0);
}

function resizeBackground(){  
  var $winwidth = $(window).width();
  if ($winwidth >= '1600'){
    var $source = bg_original;
    var $valign = 'top';
    $('#page-body').css({
      'backgroundImage': 'url(' + $source +')',
      'backgroundRepeat': 'repeat',
      'backgroundPosition': $valign + ' center'
    });
  } else {
    if (('1400' <= $winwidth) && ($winwidth < '1600')) {
      var $source = bg_1440;
    } else if (('1200' <= $winwidth) && ($winwidth < '1400')){
      var $source = bg_1280;
    } else if ((('1000' <= $winwidth) && ($winwidth < '1200') )) {
      var $source = bg_1024; 
    } else {      
      var $source = bg_800;  
    }
    $('#page-body').css({
      'backgroundImage': 'url(' + $source +')',
      'backgroundRepeat': 'repeat',
      'backgroundPosition': 'top center'
    });
  }
  
}

function destroyTeaser(){
  $.post('/teaser',
               {_method: 'delete'});  
  $('#teaser').hide();
  $('#sbi').focus();
  $('#sbi').css('background-image', 'none');
}

Preview = {
  show: function() {
    $('#show-preview').hide();
    $('#spinner').show();

    // start youtube preview
    if (typeof(YTP) != "undefined") {
      YTP.init();       
    }
    // start news preview
    if (typeof(InitNewsPreview) != "undefined") InitNewsPreview();
    
    // start bing images preview
    if (typeof(BIP) != "undefined") {
      BIP.init();       
    }

    // show boxes
    setTimeout(function() {
      if ($('.bing-image').exists() && $('#images-preview-box').exists()){
        $('#images-preview-box').show();
        $('#images-preview-box .dot').show();
      }
      if ($('.yt-video').exists() && $('#youtube-preview-box').exists()){
        $('#youtube-preview-box').show();
        $('#youtube-preview-box .dot').show();
      }
      if ($('.gs-newsResult').exists() && $('#news-preview-box').exists()){
        $('#news-preview-box').show();
        $('#news-preview-box .dot').show();
      } 
      if ($('.twtr-tweet').exists() && $('#realtime-box').exists()){
        $('#realtime-box').show();
        $('#realtime-box .dot').show();
      }  

      $('#spinner').hide();
      $('#hide-preview').show();

      $.post('/preview', {});
    }, 4000);  
  },
  hide: function() {
    $('#images-preview-box').hide();
    $('#youtube-preview-box').hide();
    $('#news-preview-box').hide();
    $('#realtime-box').hide();

    $('#hide-preview').hide();
    $('#show-preview').show(); 

    $.post('/preview', {_method: 'delete'});
  }
}

$(document).ready(function() {
  if (!($.browser.msie && parseInt($.browser.version) < 7)) {
    $(window).scroll(function() {
      positionLeftBox();
    });
    positionLeftBox();
  }

  // hilite user_login container
  $('#user_login').focus(function() {
    if ($('#user_login').val() == 'username') $('#user_login').val('');
    $('.signup-url').css('background-position', 'bottom');
  });
  $('#user_login').blur(function() {
    $('.signup-url').css('background-position', 'top');
  });

  if ($('.home-index').exists()) {
    $('#sbi').focus();
    $('#sbi').keydown(function() {
      $('#sbi').css('background-image','none');
    });
  }

  if ($('#location').exists() && ($('#location').attr('value') == '')){   
    $.get("/location", function(loc) {
      if (!loc) loc = 'San Fransisco';
      $('#location').attr('value', loc);
    });
  }

  // blink cursor on user homepage
  if (($('.themes-show').exists())) {
    $('#sbi').focus();
  }   

  if (!($('.searches-show').exists())){   
    $(window).resize(function() {
      resizeBackground()
      centerizeSearch();
    });
    resizeBackground();
    centerizeSearch();
  }
      
  /* start images search */
  if (typeof(GI) != "undefined") GI.init();
  
  /* start wikipedia search */
  if (typeof(WP) != "undefined") WP.init();
    
  /* start twitter search */
  if (typeof(TW) != "undefined") {
    TW.init();       
  } 
  
  /* start twitter search */
  if (typeof(TR) != "undefined") {
    TR.init();       
  }
     
  /* start youtube search */
  if (typeof(YT) != "undefined") {
    YT.init();       
  }
  
  /* start digg search */
  if (typeof(DG) != "undefined") {
    DG.init();       
  }
  
  /* start Yahoo Answer search */
  if (typeof(YA) != "undefined") {
    YA.init();       
  }
  
  /* start Yelp search */
  if (typeof(YP) != "undefined") {
    setTimeout(function() {
      YP.init()
      $('h2.results').html($('h2.results').html() + " near '" + $('#location').attr('value') + "'");
    }, 1500);
  }
  
  /* start Last.fm search */
  if (typeof(LF) != "undefined") {
    LF.init();       
  }
  
  /* start Bing search */
  if (typeof(BS) != "undefined") {
    BS.init();       
  }
  
  /* start Bing Images search */
  if (typeof(BI) != "undefined") {
    BI.init();       
  }
  
  /* start Yahoo search */
  if (typeof(YO) != "undefined") {
    YO.init();       
  }
    
  /* start Flickr search */
  if (typeof(F) != "undefined") {
    F.init();       
  }

  /* start DeviantArt search */
  if (typeof(DA) != "undefined") {
    DA.init();       
  }
  
  if ($('.amazon').exists()){
    setTimeout(function() {
        if ($('.dots').exists()){
          $('.dots').hide();
        } 
      }, 5000);
  }

  if ($.browser.mozilla && $('#make-homepage').exists()) {    
    $('#make-homepage').show();
  }
  
  if (document.location.href.match('#share') && $('#one-teaser').exists()) {
    $('#one-teaser').show();
  }   
    
  // AUTOFOCUS FIRST INPUT ON SIGNUP/LOGIN PAGE
	if ($(".users-new").exists() || $(".users-create").exists()) {
    $('#user_login').focus(function() { this.value = ''; });
    $('#user_login').focus();
	}
	if ($("#login").exists()) {
    $('#login').focus();
	}

  // SEARCH MORE
	if ($("#morebutton").exists()) {
    $('#morebutton').click( function() {
      $("#morelist").toggle();
    });
	}

  // USER FORM
  if ($('.user-form').exists()) {
    // check user-name availability
    $('#check_name').click( function() {
      var name = $('#user_login').attr('value');
      if ((name == '') || (name == 'username')) {
        alert('please enter a username!');
        $('#user_login').click();
        $('#user_login').focus();
      } else {
        if ($('.error').exists()){
          $('.error').hide();
        }
        $('.check_avail_spinner').show();
        $.getJSON("/users/check_availability?id="+name, function(user) {
          if (user.available) {
            $('#availability').html('available!').css('color','green');
          } else {
            $('#availability').html('already been taken!').css('color','red');
          }
        });
        $('.check_avail_spinner').hide();
      } 
    });
  }
  	
  // THEME FORM
	if ($('.theme-form').exists()) {
    var oldname = $('#theme_name').attr('value');

    // check theme-name availability
    $('#check_name').click( function() {
      var name = $('#theme_name').attr('value');
      if ((name == '') || (name == 'username')) {
        alert('please enter a username!');
        $('#theme_name').click();
        $('#theme_name').focus();
      } else if (name != oldname) {
        if ($('.error').exists()){
          $('.error').hide();
        }
        $('.check_avail_spinner').show();
        $.getJSON("/themes/check_avail?id="+name, function(theme) {
          if (theme.available) {
            $('#availability').html('available!').css('color','green');
          } else {
            $('#availability').html('already been taken!').css('color','red');
          }
        });
        $('.check_avail_spinner').hide();
      } else {
        alert('Change a username before checking!');
      }
    });

    // grab image url
    $('#grab_url').click( function() {
      var url = $('#theme_background_url').attr('value');
      $('.grab_selected').html('<img src="'+url+'"/>');
      if ($('.grab_selected > img').attr('complete') == false) {
        // bad url? fetch from the domain name instead using getJSON
        $('.grab_selected').html('');
        $('.grab_browser').html('');

        // ask from server
        $('.grab_spinner').toggle(function() {
          $.getJSON("/themes/grab?url="+url, function(images) {
            $('.grab_spinner').hide();
            for (i in images) {
              $('.grab_browser').append('<img src="'+images[i].src+'"/>');
            };
            $('.grab_browser').slideDown('slow');
            // make images clickable
            $('.grab_browser > img').click( function() {
              $('.grab_selected').html('<img src="'+this.src+'"/>');
              $('#theme_background_url').attr('value', this.src);
              $('.grab_browser').slideUp('slow');
            });
          });          
        });
      }
    });

    // upload spinner
    $('.theme-form').submit( function() {      
      $('.upload_spinner').show();
      $('.uploadbtn').hide();
      $('.uploadback').hide();
    });
  }

  // ON NEW THEME PAGE
	if ($(".themes-new").exists()) {
    // clear theme-name on click
    $('#theme_name').click( function() {
      this.value = '';
    });
	}
  
  // FLASH NOTICE
  if ($('#notice').exists()){
    $('#notice').slideDown('slow');   
    $('#notice').fadeTo(2000, 0.8);    
    $('#notice').slideUp('slow')
  }
  
  // TEASER
  if ($('#teaser').exists()){ 
    if ($.browser.msie){      
      $('#teaser').animate({opacity:0.9}, 10000);       
    }  else {
      $('#teaser').animate({opacity:0}, 2000);  
      $('#teaser').animate({opacity:0.9}, 0);
      $('#teaser').animate({opacity:0.9}, 12000);      
    }
  }
      
  $("a#make-homepage").click(function(){  
    $("#lightbox, #lightbox-panel").fadeIn(300);  
  });  
  $("a#close-panel").click(function(){  
    $("#lightbox, #lightbox-panel").fadeOut(300);
  });  
  $("a#website-url").click(function(){  
    $("#website, #mask").fadeIn(300);  
  });  
  $("a#close-website").click(function(){  
    $("#website, #mask").fadeOut(300);  
  });  
  
  $("a#share-favitt").click(function(){  
    $("#share-favitt-links").slideToggle();  
  });
  $("img#image-actions").click(function(){  
    if ($("#actions").is(':hidden')){
      $("#actions").slideToggle();  
    }
  })
  $("a#close-actions").click(function(){  
    if ($("#actions").is(':visible')){
      $("#actions").slideToggle();  
    }  
  });

  // ON LINKS EDIT PAGE
	if ($(".links-index").exists()) {
    bindLinkEvents();
    $('#links-container').sortable({
      update: function(event, ui) {
        $.post('/link_order',
               {_method: 'put', order: $('#links-container').sortable('toArray').toString()});
      }
    });
    $('li form').submitWithAjax();
	}
  
  $("img#fav").click(function(){  
    if ($("#links").is(':hidden')){
      $("#links").slideToggle();  
    }
  });
  $("a#close-links").click(function(){  
    if ($("#links").is(':visible')){
      $("#links").slideToggle();  
    }  
  }); 
  
  if ($('#one-teaser').exists()){ 
    $('#one-teaser').animate({opacity:0.9}, 0);  
  }
  $("a#close-bubble").click(function(){  
    if ($("#one-teaser").is(':visible')){
      $("#one-teaser").hide();
      removeAnchor();      
    }  
  });
  
  $("a#thanks-bubble").click(function(){  
    if ($("#one-teaser").is(':visible')){
      $("#one-teaser").hide();
      removeAnchor();
    }  
  });
  
  if ($('.searches-show').exists()){
    $('#hide-preview').click(function() { Preview.hide(); });
    $('#show-preview').click(function() { Preview.show(); });

    if (hidePreview) {
      Preview.hide();
    } else {
      Preview.show();
    }

    if ($('.amazon').exists()){
      $('#summary').hide();
      setTimeout(function() {
        if ($('.wdgt_tl_pad').exists()){
          $('#summary').html('<span class="more"><a href="http://www.amazon.com/s/ref=nb_sb_noss?field-keywords=' + $('#sbi').attr('value') + '">more from amazon</a> &rarr;</span><div class="clr"></div>');
          $('#summary').show();
        } 
      }, 5000);
    }    
  }
  
  if ($(".user_engines-index").exists()) {
    bindUserEngineEvents();    
    $('li form').submit(function() {
      $.post(this.action, $(this).serialize(), null, "script");
      return false;
    });    
	}
  

});

bindLinkEvents = function() {
  $('.link > a').click( function() {
    id = this.id.split('-')[1];
    $('#link-' + id).hide();
    $('#link-edit-' + id).show();
  });
  $('.cancel').click( function() {
    id = this.id.split('-')[1];
    $('#link-edit-' + id).hide();
    $('#link-' + id).show();
  });
  $('.del').click( function() {
    id = this.id.split('-')[1];
    $('#link-edit-' + id + ' .text').attr('value', '');
  });
}

bindUserEngineEvents = function() {
  $('.user_engine > a').click( function() {
    id = this.id.split('-')[1];
    $('#user_engine-' + id).hide();
    $('#user_engine-edit-' + id).show();
  });
  $('.cancel').click( function() {
    id = this.id.split('-')[1];
    $('#user_engine-edit-' + id).hide();
    $('#user_engine-' + id).show();
  });
  $('.del').click( function() {
    id = this.id.split('-')[1];
    $('#user_engine-edit-' + id + ' .text').attr('value', '');
  });
  $("a#close-teaser").click(function(){  
    $("#engine-teaser").fadeOut(300);
  });
  
  $(".user_engine_name").keydown(function(e){
    if (e.which == 8 || e.which == 13) return true;
    if ($(this).attr('value').length > 11) {
      $(this).attr('value', $(this).attr('value').substr(0,11));
      alert('sorry only 12 characters allowed');
      return false;
    }    
  });
}

jQuery.fn.exists = function() {
	if (jQuery(this).length > 0) {
		return true;
	} else {
		return false;
	}
};

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  });
  return this;
};

function autolink(s) 
{   
   var hlink = /\s(ht|f)tp:\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
   return (s.replace (hlink, function ($0,$1,$2) { s = $0.substring(1,$0.length); 
                                                   // remove trailing dots, if any
                                                   while (s.length>0 && s.charAt(s.length-1)=='.') 
                                                      s=s.substring(0,s.length-1);
                                                   // add hlink
                                                   return " " + s.link(s); 
                                                 }
                     ) 
           );
}

function formatPhoneNumber(num) {
        if(num.length != 10) return '';
        return '(' + num.slice(0,3) + ') ' + num.slice(3,6) + '-' + num.slice(6,10) + '<br/>';
    }
    
function pongSearch(data){
  if (data.total > 0){
    DG.r.html('');
    var totalPage = Math.round(data.total/10);
    from = (DG.p - 1) * 10 + 1;
    to   = from + 9;
    $('#summary').html('<span class="more"><a href="http://digg.com/search?s=' + escape(DG.q.attr('value')) + '">more from digg</a> &rarr;</span> Displaying ' + from + '-' + to + ' out of ' + data.total);
    $.each(data.stories, function(i,result){ 
      var digg_html = '<li><div class="diggs"><span class="diggcount">' + result.diggs + '</span><br/>diggs</div>';
      digg_html += '<a href="' + result.shorturl.short_url + '">' + result.title + '</a>';
      digg_html += '<br/>' + result.description.substr(0,180)
      digg_html += ' (<span class="diggby">Submitted by ' + result.user.name + '</span>).</li><div class="clr"></div>';                
      $("#diggresults").append(digg_html); 
    });
    $('.contentingog').append('<div class="pagination"></div>');
    pg = $('.pagination');
    if (DG.p > 1) {
      p = '<a href="javascript:DG.pingSearch(' + (DG.p - 1) +')">&laquo; Previous</a>';                
    } else {
      p = '<span></span>';
    }       
    if (DG.p < totalPage) {
      n = '<a href="javascript:DG.pingSearch('+ (DG.p + 1) + ')">Next &raquo;</a>';
    } else {
      p = '<span></span>';
    }
    pg.append(p);
    pg.append(n);               
    DG.r.append(pg);
    $(window).scrollTop(0);
  } else {
    $('h3#summary').html('Your search - ' +  DG.q.attr('value') + ' - did not match any documents.');
    DG.r.append('<h4>Suggestions:</h4>');
    DG.r.append('<ul class="suggestion"><li>Be sure all words are spelled correctly.</li><li>Try different keywords.</li><li>Try more general keywords.</li></ul>');                
  }    
  $('.dots').hide();
}

function pongISearch(data){  
  if (data.responseData.cursor.estimatedResultCount > 0){    
    GI.r.html(''); 
    $('.pagination').html('');
    var totalPage = Math.round(data.responseData.cursor.estimatedResultCount/16);     
    from = (GI.p - 1) * 8 + 1;    
    to   = from + 15;
    $('#summary').html('<span class="more"><a href="http://images.google.com/images?q=' + escape(GI.q.attr('value')) + '">more from images</a> &rarr;</span> Displaying ' + from + ' - ' + to + ' of ' + data.responseData.cursor.estimatedResultCount);
    $.each(data.responseData.results, function(i,result){ 
      var images_html = '<li class="images"><a href = "' + result.originalContextUrl; 
      images_html += '"><img src="'+ result.url +'"></img></a>';      
      images_html += '<br/>' + result.title.substr(0,20);
      images_html += '<br/><span>' + result.width + ' x ' + result.height  + '</span>';
      images_html += '<br/><a href="' + result.originalContextUrl + '">' + result.visibleUrl + '</a>';
      images_html += '</li>';
      $("#videos").append(images_html); 
    });  
    if (typeof(GII) != "undefined") GII.init();    
  } else {
    $('h3#summary').html('Your search - ' +  GI.q.attr('value') + ' - did not match any documents.');
    GI.r.append('<h4>Suggestions:</h4>');
    GI.r.append('<ul class="suggestion"><li>Be sure all words are spelled correctly.</li><li>Try different keywords.</li><li>Try more general keywords.</li></ul>');                
  }   
  $('.dots').hide();  
}

function pongIISearch(data){  
  if (data.responseData.cursor.estimatedResultCount > 0){    
    var totalPage = Math.round(data.responseData.cursor.estimatedResultCount/16);    
    $.each(data.responseData.results, function(i,result){ 
      var images_html = '<li class="images"><a href = "' + result.originalContextUrl; 
      images_html += '"><img src="'+ result.url +'"></img></a>';      
      images_html += '<br/>' + result.title.substr(0,20);
      images_html += '<br/><span>' + result.width + ' x ' + result.height  + '</span>';
      images_html += '<br/><a href="' + result.originalContextUrl + '">' + result.visibleUrl + '</a>';
      images_html += '</li>';
      $("#videos").append(images_html); 
    });
    $('.contentingog').append('<div class="pagination"></div>');
    pg = $('.pagination');
    if (GII.p > 2) {       
      var prev = '<a href="javascript:GI.pingSearch(' + (GII.p - 3) +')">&laquo; Previous</a>';                
    } else {
      var prev = '<span></span>';
    }       
    if (GII.p < totalPage) {      
      var next = '<a href="javascript:GI.pingSearch(' + (GII.p + 1) +')">Next &raquo;</a>';
    } else {
      var prev = '<span></span>';
    }
    pg.append(prev);
    pg.append(next);               
    GI.r.append(pg);
  } else {
    $('h3#summary').html('Your search - ' +  GI.q.attr('value') + ' - did not match any documents.');
    GII.r.append('<h4>Suggestions:</h4>');
    GII.r.append('<ul class="suggestion"><li>Be sure all words are spelled correctly.</li><li>Try different keywords.</li><li>Try more general keywords.</li></ul>');                
  }    
  $('.dots').hide();
}

