// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/*** capslock warning for passwords ***/
$(function(){
  $("input[type='password']").keypress(function (e){
    var k = e.keyCode || e.charCode;
    var cl = ((k >= 97 && k <= 122) && e.shiftKey) || ((k >= 65 && k <= 90) && !e.shiftKey);
    $('.capslock').css('display', 'none');
    $(this).next().filter('.capslock').css('display', cl?'inline':'none');
    return true;
  }).after(" <span class='capslock' style='display: none'>You seem to have capslock key turned on.</span>");
});

/*** image zoom ***/
$(function($){
  /* This is called after every mouseover in case user changed zoom level or window size etc. */
  var fix_mouseover_box_placement = function(box) {
    var relative_to = $(box).parents().filter(".zoomable_thumbnail");
    var relative_to_page = relative_to.offset().top;
    var footer = $(".footer");
    var bh = box.height();
    
    var image = $(box).find("img.full_preview")[0];
    
    /* Firefox reports unloaded images as 0x0, IE8 reports them as 28x28 (size of missing image pic...) */
    if(image && image.width >= 64 && image.height >= 64) {
      if(!$(image).data('originalWidth')) {
        $(image).data('originalWidth', image.width);
      }
      
      var ww = $(window).width();
      var bw = $(box).width();
      var bx = $(box).offset().left;
      var iw = $(image).data('originalWidth');

      /* If right side is too far */
      var maximum_reasonable_width = ww - bw - bx + image.width - 10;
      if(maximum_reasonable_width > iw) maximum_reasonable_width = iw;
      if(maximum_reasonable_width < image.width || image.width != iw) {
        image.width = maximum_reasonable_width;
      }
    }
    
    /* Don't go out of window */
    var scroll_top = Math.max(window.document.documentElement.scrollTop, window.document.body.scrollTop);
    /* Everything that's not IE */
    var inner_height = window.innerHeight;
    /* IE6+ in strict mode, will fail in quirks mode and in IE<6*/
    if(inner_height === undefined) {
      inner_height = document.documentElement.clientHeight;
    }


    // Align central line of image with central line of thumbnail
    var optimal = relative_to_page + 25 - bh/2;
    var min_window = scroll_top + 10;
    var max_window = scroll_top + inner_height - 10 - bh;

    // Now this could be outside viewing window - something we do not want to happen
    var top_overflow = min_window - optimal;
    var bottom_overflow = optimal - max_window;

    /* Either top or bottom has some margins left */
    if(top_overflow > 0 && bottom_overflow < 0) {
      optimal += Math.min(top_overflow, -bottom_overflow);
    } else if (top_overflow < 0 && bottom_overflow > 0) {
      optimal -= Math.min(bottom_overflow, -top_overflow);
    }

    /* Margins exhausted, let's just center it then */
    top_overflow    = min_window - optimal;
    bottom_overflow = optimal - max_window;
    
    optimal += Math.max(top_overflow, 0) / 2;
    optimal -= Math.max(bottom_overflow, 0) / 2;
    
    box.css('top', (optimal - relative_to_page) + 'px');
  };

  /* CSS doesn't have any way of resizing image to fit a box while preserving its aspect ratio */
  $("img.thumbnail").each(function(){
    var thumb = this;
    var i = new Image();
    i.onload = function() {
      if(i.width !== 0 && i.height !== 0) {
        var wscale = 65 / i.width;
        var hscale = 50 / i.height;
        var scale = Math.min(1, Math.min(wscale, hscale));
        var w = Math.round(scale * i.width);
        var h = Math.round(scale * i.height);
        $(thumb).css('height', h).
                 css('width', w).
                 css('margin-left', Math.floor((65-w)/2)).
                 css('margin-right', Math.ceil((65-w)/2)).
                 css('margin-top', Math.ceil((50-h)/2)).
                 css('margin-bottom', Math.ceil((50-h)/2));
      }
    }
    i.src = thumb.src;
  });
  /* Workaround for double scrollbar bug */
  $("img.full_preview").each(function() {
    var box = $(this).parents().filter(".full_preview_box");
    $(this).load(function(){fix_mouseover_box_placement(box)}); /* If not loaded yet */
    if(this.width !== 0 && this.height !== 0) {
      fix_mouseover_box_placement(box); /* If already loaded */
    }
  });

  var timeout_var = null;
  var hide_boxes = function() {
    $(".zoomable_thumbnail").removeClass('in_focus');
    $(".hints_box").hide();
    $(".bubble").hide();
    if(timeout_var) {
      clearTimeout(timeout_var);
      timeout_var = null;
    }
  }
  
	$(".thumbnail").mouseover(function() {
	  hide_boxes();
	  var result = $(this).parents().filter(".zoomable_thumbnail");
	  fix_mouseover_box_placement(result.find(".full_preview_box"));
	  result.addClass('in_focus');
	}).mouseout(function(){
	  timeout_var = setTimeout(hide_boxes, 200);
	}).after("<img class='zoom_icon' src='/images/zoom_in.gif' />");

  $(".result_main .full_preview_box").mouseover(function(){
    if(timeout_var) {
      clearTimeout(timeout_var);
      timeout_var = null;
    }
  }).mouseout(function(){
    timeout_var = setTimeout(hide_boxes, 200);
  });

  $(".affiliate_zoom_icon").mouseover(function() {
	  hide_boxes();
    var af = $(this).parents().filter(".affiliate_link");
	  fix_mouseover_box_placement(af.find(".full_preview_box"));
    af.addClass('in_focus');
  }).mouseout(function(){
    $(".zoomable_thumbnail").removeClass('in_focus');
  });

	$(".preview_off").click(hide_boxes);
});

/*** advanced search dropdowns ***/
$(function($){
  $("#advanced_doc_date").change(function(){
    var d = $("#advanced_doc_date").val();
    var t = $("#advanced_doc_type").val();
    if(d !== "all" && (t == "all" || t == "image" || t == "table")){
      $("#advanced_doc_type").val('dated');
    }
  });
  $("#advanced_doc_type").change(function(){
    var d = $("#advanced_doc_date").val();
    var t = $("#advanced_doc_type").val();
    if(d !== "all" && (t == "all" || t == "image" || t == "table")){
      $("#advanced_doc_date").val('all');
    }
  });
});

/*** query parser hints ***/
$(function($){
  if($.browser.mozilla && $.browser.version < '1.9') { return; } // Firefox 2.0 not supported
  if($.browser.msie && $.browser.version < '8.0') { return; } // IE6/7 too buggy, not supported for now
  var stopwords = {"will":true, "it":true, "of":true, "no":true, "by":true, "but":true, "and":true,
                   "into":true, "an":true, "or":true, "be":true, "to":true, "in":true, "the":true,
                   "these":true, "such":true, "if":true, "as":true, "there":true, "their":true,
                   "a":true, "s":true, "not":true, "at":true, "was":true, "then":true, "that":true, "t":true,
                   "on":true, "for":true, "are":true, "with":true, "this":true, "they":true, "is":true,
                   "about":true,
                   "from":true,
                   "out":true,
                   "too":true,
                   "under":true,
                   "very":true,
                   "what":true,
                   "which":true,
                   'per':true,
                   "among":true,
                   "during":true,
                   "via":true,
                   "over":true,
                   "vs":true
                   };
  var update = function() {
    var text = $(smart).text();

    /* Being lazy fixes backwards selection problem. Or works around it at least. */
    if(old_text !== null && old_text === text){return;}
    old_text = text;

    input.val(text.replace(/[\s\u00a0\u2002-\u200d]/g, " "));
    
    // IE handles spaces correctly
    // everything else collapses normal spaces (sometimes) but leaves Unicode spaces intact
    // Opera collapses all spaces (hopefully except &nbsp;)
    if($.browser.opera) {
      text = text.replace(/[\s\u00a0\u2002-\u200d]/g, "\u00a0");
    } else if(!$.browser.msie) {
      text = text.replace(/[\s\u00a0\u2002-\u200d]/g, "\u2005");
    }
    var parts = text.match(/[\s\u00a0\u2002-\u200d,\?()]+|"[^"]*"|[^\s\u00a0\u2002-\u200d,\?()]+/g) || [];

    // [\s\u00a0\u2002-\u200d] should be just \s, but some browsers don't know about Unicode spaces
    var from = null, to = null;
    try{
      from = select.cursorPos(smart, true);
      to = select.cursorPos(smart, false);
    } catch (e) {
      // Sometimes happen during first run
    }

    $(smart).empty();
    
    for(var i=0, mandatory=0; i<parts.length; i++) {
      var part = parts[i];
      var doc = smart.ownerDocument||document;
      var tn = doc.createTextNode(part);
      var nn = null;
      if(!/[^\s\u00a0\u2002-\u200d,\?()]/.test(part)) { // no non-whitespace (some whitespace ok in "foo bar")
        nn = tn; // No magic
      } else if(part.length <= 1 || stopwords[part.toLowerCase()]) { // stopword
        var nn = $("<span class='stopword'></span>")[0];
        nn.appendChild(tn);
      } else if(/^(site|type|date|country):(.*)/i.test(part)) { // special
        var nn = $("<span class='special'></span>")[0];
        nn.appendChild(tn);
      } else if(/^-/.test(part)){
        var nn = $("<span class='prohibited'></span>")[0];
        nn.appendChild(tn);
      } else if(/^\+/.test(part) || mandatory < 2) {
        var nn = $("<span class='mandatory'></span>")[0];
        nn.appendChild(tn);
        mandatory++;
      } else {
        nn = tn;
      }
      smart.appendChild(nn);
    }
    if(from !== null && to !== null) { select.setCursorPos(smart, from, to); }
  };
  var intercept = function(event) {
    if(event.keyCode == 13) {
			event.preventDefault();
			event.stopPropagation();
      $("#search_form").submit();
      return false;
    }
  }
  var old_text = null;
  var input = $("#input_search");

  if(input.length === 0) { return; } // Not a page with search form

  var smart = $("<div id='input_search_smart' contentEditable='true'></div>")[0];
  $(input).hide();
  $(input).after(smart);
  $(smart).keyup(update); // should happen post-keypress (or simply periodically)
  $(smart).keydown(intercept);
  var v = input.val();
  if(v == "") v = " ";
  $(smart).text(v);

  smart.focus();
  setInterval(update, 1000);
  update();
});

/*** quicklinks ***/
$(function($){
  if($("#search_form").length) {
    $(".quicklinks").append('<a href="#" class="hints_toggle">Hints</a>');
    $(".hints_toggle").click(function(){
      if($(".hints_box:visible").length) {
        $(".hints_box").hide();
      } else {
        $(".hints_box").show();
    	  $(".zoomable_thumbnail").removeClass('in_focus');
      }
    });
    $(".hints_off").click(function(){ $(".hints_box").hide(); });
  }
  if($("body.white-label").length == 0) {
    if($.browser.mozilla) {
      if($("#header .quicklinks a").length) { $("#header .quicklinks").append('<span class="separator"></span>'); }
      $("#header .quicklinks").append('<a href="/zanranforgoogle.xpi">Firefox plug-in</a>');
    } else if($.browser.msie){
      if($("#header .quicklinks a").length) { $("#header .quicklinks").append('<span class="separator"></span>'); }
      $("#header .quicklinks").append('<a href="#" class="add_bookmark">Add to Favorites</a>');
      $(".add_bookmark").click(function(){
        window.external.AddFavorite("http://www.zanran.com/", "Zanran Numerical Data Search");
      });
    }
  }
});


/*** Advanced/debug search toggle ***/
$(function($){
  $("#advanced_search_on").click(function(){
    $("#search_form").addClass('show_advanced_search').removeClass('hide_advanced_search');
    $("#advanced_search_options :input").attr('disabled', false);
    $(".filter_hints").hide();
    return false;
  });
  $("#advanced_search_off").click(function(){
    $("#search_form").addClass('hide_advanced_search').removeClass('show_advanced_search');
    $("#advanced_search_options :input").attr('disabled', true);
    return false;
  });
  $("#debug_search_on").click(function(){
    $("#search_form").addClass('show_debug_search').removeClass('hide_debug_search');
    $("#debug_search_options :input").attr('disabled', false);
    return false;
  });
  $("#debug_search_off").click(function(){
    $("#search_form").addClass('hide_debug_search').removeClass('show_debug_search');
    $("#debug_search_options :input").attr('disabled', true);
    return false;
  });

  $(".filter_hint a.automatic_filter").click(function(){
    $("#search_form").addClass('show_advanced_search').removeClass('hide_advanced_search');
    $("#advanced_search_options :input").attr('disabled', false);
    $(".filter_hints").hide();
    // var country = this.getAttribute('data-advanced-country');
    // var date = this.getAttribute('data-advanced-date');
    // if(country) {
    //   $("#advanced_country").val(country);
    // }
    // if(date) {
    //   $("#advanced_doc_date").val(date);
    // }
    return false;
  });
});

/*** External links tracking ***/
$(function($) {
  $("tr.result_main, tr.result_sec").each(function(){
    var rn = this.getAttribute('data-result-number');
    var query = $("form")[0].getAttribute('data-tracker');
    var in_post = null;
    var in_click = false;
    var delayed_click = function() {
      if(in_click && in_post) { location.href = in_post; }
      in_click = false;
      in_post = null;
    };
    $(this).find("a.result_link").mousedown(function(){
      in_post = this.href;
      $.post("/click", { url: this.href, number: rn, query: query }, delayed_click);
      setTimeout(delayed_click, 250);
      return true;
    }).click(function(){
      if(in_post) {
        in_click = true;
        return false;
      } else {
        return true;
      }
    });
  });
});

/*** iPhone warning ***/
$(function($) {
  if(navigator.userAgent.indexOf("iPhone") != -1) {
    $("#content").prepend("<div class='messages'><div class='mobile_warning'>Zanran is not designed to work on small screens - yet</div></div>");
  }
});
