/*
 * jQuery clueTip plugin
 * Version 0.9.8  (05/22/2008)
 * @requires jQuery v1.1.4+
 * @requires Dimensions plugin (for jQuery versions < 1.2.5)
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
;(function($) { 
/*
 * @name flyout
 * @type jQuery
 * @cat Plugins/tooltip
 * @return jQuery
 * @original cluetip author Karl Swedberg
 *
 */

  var $cluetip, $cluetipOuter, $cluetipArrows, $dropShadow, imgCount;
  var $cluetipTC, $cluetipTR, $cluetipTL, $cluetipHeading, $cluetipClose, $cluetipContent, $cluetipMC, $cluetipMR, $cluetipML, $cluetipBC, $cluetipBR, $cluetipBL, $cluetipBW;
  $.fn.cluetip = function(js, options) {
    if (typeof js == 'object') {
      options = js;
      js = null;
    }
    return this.each(function(index) {
      var $this = $(this);      
      
      // support metadata plugin (v1.0 and 2.0)
      var opts = $.extend(false, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});

      // start out with no contents (for ajax activation)
      var cluetipContents = false;
      var cluezIndex = parseInt(opts.cluezIndex, 10)-1;
      var isActive = false, closeOnDelay = 0;

      // create the cluetip divs
      if (!$('#cluetip').length) {
        $cluetipTC = $('<div class="flyout-tc"></div>');
        $cluetipTR = $('<div class="flyout-tr"></div>').prepend($cluetipTC);
        $cluetipTL = $('<div class="flyout-tl"></div>').prepend($cluetipTR);
        
        $cluetipHeading = $('<div class="flyout-heading"></div>');
        $cluetipClose = $('<div class="flyout-close"><a href="#" /></div>');
        $cluetipContent = $('<div id="flyout-content" class="flyout-description"></div>');
        $cluetipMC = $('<div class="flyout-mc"></div>').prepend($cluetipContent).prepend($cluetipHeading).prepend($cluetipClose);
        $cluetipMR = $('<div class="flyout-mr"></div>').prepend($cluetipMC);
        $cluetipML = $('<div class="flyout-ml"></div>').prepend($cluetipMR);        
        
        $cluetipBC = $('<div class="flyout-bc"></div>');
        $cluetipBR = $('<div class="flyout-br"></div>').prepend($cluetipBC);
        $cluetipBL = $('<div class="flyout-bl"></div>').prepend($cluetipBR);    
        
		$cluetipBW = $('<div class="flyout-bwrap"></div>').prepend($cluetipBL).prepend($cluetipML);               
        
        $cluetipOuter = $('<div id="cluetip-outer"></div>').prepend($cluetipBW).prepend($cluetipTL);
        $cluetip = $('<div id="cluetip"></div>').css({zIndex: opts.cluezIndex})
        .append($cluetipOuter).append('<div id="cluetip-extra"></div>')[insertionType](insertionElement).hide();
        $('<div id="cluetip-waitimage"></div>').css({position: 'absolute', zIndex: cluezIndex-1})
        .insertBefore('#cluetip').hide();
        $cluetip.css({position: 'absolute', zIndex: cluezIndex});
        $cluetipOuter.css({position: 'relative', zIndex: cluezIndex+1});
        $cluetipArrows = $('<div id="cluetip-arrows" class="cluetip-arrows"></div>').css({zIndex: cluezIndex+1}).appendTo('#cluetip');
      }
      var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0;
      if (!$dropShadow) {
        $dropShadow = $([]);
        for (var i=0; i < dropShadowSteps; i++) {
          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: cluezIndex-i-1, opacity:.05, top: 1+i, left: 1+i}));
        };
        $dropShadow.css({position: 'absolute', backgroundColor: '#000'})
        .prependTo($cluetip);
      }
      var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;
      if (!tipAttribute && !js) return true;
      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip      
      if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }
      var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);
      // vertical measurement variables
      var tipHeight, wHeight;
      var defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';
      var sTop, linkTop, posY, tipY, mouseY, baseline;
      // horizontal measurement variables
      var tipInnerWidth = isNaN(parseInt(opts.width, 10)) ? 275 : parseInt(opts.width, 10);
      var tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'))||0) + (parseInt($cluetip.css('paddingRight'))||0) + dropShadowSteps;
      var linkWidth = this.offsetWidth;
      var linkLeft, posX, tipX, mouseX, winWidth;
            
      // parse the title
//      var tipParts;
      var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';
/*      if (opts.splitTitle) {
        if(tipTitle == undefined) {tipTitle = '';}
        tipParts = tipTitle.split(opts.splitTitle);
        tipTitle = tipParts.shift();
      }*/
      var localContent;

/***************************************      
* ACTIVATION
****************************************/
    
//activate clueTip
    var activate = function(event) {
      if (!opts.onActivate($this)) {
        return false;
      }
      isActive = true;
      $cluetip.removeClass().css({width: tipInnerWidth});
      if (tipAttribute == $this.attr('href')) {
        $this.css('cursor', opts.cursor);
      }
      $this.attr('title','');
      if (opts.hoverClass) {
        $this.addClass(opts.hoverClass);
      }
      linkTop = posY = $this.offset().top;
      linkLeft = $this.offset().left;
      mouseX = event.pageX;
      mouseY = event.pageY;
      if ($this[0].tagName.toLowerCase() != 'area') {
        sTop = $(document).scrollTop();
        winWidth = $(window).width();
      }
// position clueTip horizontally
      if (opts.positionBy == 'fixed') {
        posX = linkWidth + linkLeft + lOffset;
        $cluetip.css({left: posX});
      } else {
        posX = (linkWidth > linkLeft && linkLeft > tipWidth)
          || linkLeft + linkWidth + tipWidth + lOffset > winWidth 
          ? linkLeft - tipWidth - lOffset 
          : linkWidth + linkLeft + lOffset;
        if ($this[0].tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
          if (mouseX + 20 + tipWidth > winWidth) {  
            $cluetip.addClass(' cluetip-' + ctClass);
            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipContent.css('marginRight'),10) :  mouseX - (tipWidth/2);
          } else {
            posX = mouseX + lOffset;
          }
        }
        var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
        $cluetip.css({left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0)});
      }
        wHeight = $(window).height();

/***************************************
* load a string from cluetip method's first argument
***************************************/
      if (js) {
        $cluetipContent.html(js);
        cluetipShow(pY);
      }
/***************************************
* load external file via ajax          
***************************************/

      else if (!opts.local && !opts.extjs && tipAttribute.indexOf('#') != 0) {
        if (cluetipContents && opts.ajaxCache) {
          $cluetipContent.html(cluetipContents);
          cluetipShow(pY);
        }
        else {
          var ajaxSettings = opts.ajaxSettings;
          ajaxSettings.url = tipAttribute;
          ajaxSettings.beforeSend = function() {
            $cluetipContent.empty();
            if (opts.waitImage) {
              $('#cluetip-waitimage')
              .css({top: mouseY+20, left: mouseX+20})
              .show();
            }
          };
         ajaxSettings.error = function() {
            if (isActive) {
              $cluetipContent.html('<i>sorry, the contents could not be loaded</i>');
            }
          };
          ajaxSettings.success = function(data) {
            cluetipContents = opts.ajaxProcess(data);
            if (isActive) {
              $cluetipContent.html(cluetipContents);
            }
          };
          ajaxSettings.complete = function() {
        		if (imgCount && !$.browser.opera) {
        		  $cluetipContent.load(function() {
          				$('#cluetip-waitimage').hide();
          			  if (isActive) cluetipShow(pY);
          			}); 
        		} else {
      				$('#cluetip-waitimage').hide();
        		  if (isActive) cluetipShow(pY);    
        		}
          };
          $.ajax(ajaxSettings);
        }

/***************************************
* load an element from the same page
***************************************/
      } else if (opts.local){
        var $localContent = $(tipAttribute + ':first'); 
        var localCluetip = $localContent.html();	
        $cluetipContent.html(localCluetip);        
/*        var localCluetip = $.fn.wrapInner ? $localContent.wrapInner('<div></div>').children().clone(true) : $localContent.html();	
        $.fn.wrapInner ? $cluetipContent.empty().append(localCluetip) : $cluetipContent.html(localCluetip);*/
        cluetipShow(pY);

    /***************************************
* load an element from the same page after update in extjs
***************************************/
      } else if (opts.extjs){
    	var val = $(opts.extjsActiveClass+':first').attr('record');
    	var coll = auctionCatalogStore.query('lotId',val);        	
        $cluetipContent.html(renderCatalogFlyout(coll));  
        cluetipShow(pY);
      }
    };

// get dimensions and options for cluetip and prepare it to be shown
    var cluetipShow = function(bpY) {
      $cluetip.addClass('cluetip-' + ctClass);
      
/*      if (opts.truncate) { 
        var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...';
        $cluetipInner.html($truncloaded);
      }*/
      function doNothing() {}; //empty function
      tipTitle ? $cluetipHeading.show().html(tipTitle) : (opts.showTitle) ? $cluetipHeading.show().html('&nbsp;') : $cluetipHeading.hide();
      if (opts.sticky) {
        $cluetipClose.click(function() {
          cluetipClose();
          return false;
        });
        if (opts.mouseOutClose) {
          if ($.fn.hoverIntent && opts.hoverIntent) { 
            $cluetip.hoverIntent({
              over: doNothing, 
              timeout: opts.hoverIntent.timeout,  
              out: function() { $cluetipClose.trigger('click'); }
            });
          } else {
            $cluetip.hover(doNothing, 
            function() {$cluetipClose.trigger('click'); });
          }
        } else {
          $cluetip.unbind('mouseout');
        }
      }
// now that content is loaded, finish the positioning 
      var direction = '';
      $cluetipOuter.css({overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});
      tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10);   
      tipY = posY;
      baseline = sTop + wHeight;
      if (opts.positionBy == 'fixed') {
        tipY = posY - opts.dropShadowSteps + tOffset;
      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {
        if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) { 
          tipY = mouseY - tipHeight - tOffset;
          direction = 'top';
        } else { 
          tipY = mouseY + tOffset;
          direction = 'bottom';
        }
      } else if ( posY + tipHeight + tOffset > baseline ) {
        tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;
      } else if ($this.css('display') == 'block' || $this[0].tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {
        tipY = bpY - tOffset;
      } else {
        tipY = posY - opts.dropShadowSteps;
      }
      if (direction == '') {
        posX < linkLeft ? direction = 'left' : direction = 'right';
      }
      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
		if (opts.arrows) 
		{ // set up arrow positioning to align with element
	        var bgY = (posY - tipY - opts.dropShadowSteps);
		
	        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();
	        if(opts.positionBy == 'bottomTop') {
		  $cluetipArrows.css({top: '-36px'});
		}
		var left_css = ' cluetip-arrows-left';
	        var right_css = ' cluetip-arrows-right';
	      	var bg_class = (/(left|right)/.test(direction)) ? 
	      									(direction == 'right'? right_css : left_css ) : '';
	      									
	      	if(bg_class == left_css){
	      		$cluetipArrows.removeClass(right_css);
	      	}else{
	      		$cluetipArrows.removeClass(left_css);
	      	}
	      	
	      	$cluetipArrows.addClass(bg_class);
	      
      	
      } else {
        $cluetipArrows.hide();
      }

// (first hide, then) ***SHOW THE CLUETIP***
      $dropShadow.hide();
      $cluetip.hide()[opts.fx.open](opts.fx.open != 'show' && opts.fx.openSpeed);
      if (opts.dropShadow) $dropShadow.css({height: tipHeight, width: tipInnerWidth}).show();
      if ($.fn.bgiframe) { $cluetip.bgiframe(); }
      // trigger the optional onShow function
      /*if (opts.delayedClose > 0) {
        closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);
      }*/
      opts.onShow($cluetip, $cluetipContent);
      
    };

/***************************************
   =INACTIVATION
-------------------------------------- */
    var inactivate = function() {
      isActive = false;
      $('#cluetip-waitimage').hide();
      if (!opts.sticky || (/click|toggle/).test(opts.activation) ) {
        cluetipClose();
clearTimeout(closeOnDelay);        
      };
      if (opts.hoverClass) {
        $this.removeClass(opts.hoverClass);
      }
      $('.cluetip-clicked').removeClass('cluetip-clicked');
    };
// close cluetip and reset some things
    var cluetipClose = function() {
      /*$cluetipOuter 
      .parent().hide().removeClass().end()
      .children().empty();*/
      $cluetipOuter.parent().hide();
      $cluetipHeading.empty();
      $cluetipContent.empty();
      
      if (tipTitle) {
        $this.attr(opts.titleAttribute, tipTitle);
      }
      $this.css('cursor','');
      if (opts.arrows) $cluetipArrows.css({top: ''});
    };

/***************************************
   =BIND EVENTS
-------------------------------------- */
  // activate by click
      if ( (/click|toggle/).test(opts.activation) ) {
        $this.click(function(event) {
          if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {
            activate(event);
            $('.cluetip-clicked').removeClass('cluetip-clicked');
            $this.addClass('cluetip-clicked');

          } else {
            inactivate(event);

          }
          this.blur();
          return false;
        });
  // activate by focus; inactivate by blur    
      } else if (opts.activation == 'focus') {
        $this.focus(function(event) {
          activate(event);
        });
        $this.blur(function(event) {
          inactivate(event);
        });
  // activate by hover
    // clicking is returned false if cluetip url is same as href url
      } else {
        $this.click(function() {
          if ($this.attr('href') && $this.attr('href') == tipAttribute && !opts.clickThrough) {
            return false;
          }
        });
        if ($.fn.hoverIntent && opts.hoverIntent) {
          $this.mouseover(function() {$this.attr('title',''); })
          .hoverIntent({
            sensitivity: opts.hoverIntent.sensitivity,
            interval: opts.hoverIntent.interval,  
            over: function(event) {
              activate(event);
              //mouseTracks(event);
            }, 
            timeout: opts.hoverIntent.timeout,  
            out: function(event) {inactivate(event); $this.unbind('mousemove');}
          });           
        } else {
          $this.hover(function(event) {
            activate(event);
            //mouseTracks(event);
          }, function(event) {
            inactivate(event);
            $this.unbind('mousemove');
          });
        }
      }
    });
  };
  
/*
 * options for clueTip
 */
  
  $.fn.cluetip.defaults = {  // set up default options
    width:            400,      // The width of the clueTip
    height:           'auto',   // The height of the clueTip
    cluezIndex:       97,       // Sets the z-index style property of the clueTip
    positionBy:       'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'
    topOffset:        15,       // Number of px to offset clueTip from top of invoking element
    leftOffset:       15,       // Number of px to offset clueTip from left of invoking element
    extjs:            false,    // same as local - used to update with extjs
    extjsActiveClass: 'a.flyout-active',	//the active class of the element that triggers the flyout
    local:            false,    // Whether to use content from the same page for the clueTip's body
    hideLocal:        true,     // If local option is set to true, this determines whether local content
                                // to be shown in clueTip should be hidden at its original location
    attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content
    titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title    
    showTitle:        true,     // show title bar of the clueTip, even if title attribute not set
    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.
    hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout
    waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
    cursor:           'pointer',
    arrows:           true,    // if true, displays arrow on appropriate side of clueTip
    dropShadow:       true,     // set to false if you don't want the drop-shadow effect on the clueTip
    dropShadowSteps:  5,        // adjusts the size of the drop shadow
    sticky:           true,    // keep visible until manually closed
    mouseOutClose:    true,    // close when clueTip is moused out
    activation:       'hover',  // set to 'click' to force user to click to show clueTip
                                // set to 'focus' to show on focus of a form element and hide on blur
    clickThrough:     false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,
                                // even if href and tipAttribute are equal
    closePosition:    'title',    // location of close text for sticky cluetips; can only be set to 'title'

    // effect and speed for opening clueTips
    fx: {             
                      open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
                      openSpeed:  ''
    },     

    // settings for when hoverIntent plugin is used             
    hoverIntent: {    
                      sensitivity:  3,
              			  interval:     50,
              			  timeout:      0
    },

    // function to run just before clueTip is shown.           
    onActivate:       function(e) {return true;},

    // function to run just after clueTip is shown.
    onShow:           function(ct, c){},
    
    // whether to cache results of ajax request to avoid unnecessary hits to server    
    ajaxCache:        true,  

    // process data retrieved via xhr before it's displayed
    ajaxProcess:      function(data) {
                        data = data.replace(/<s(cript|tyle)(.|\s)*?\/s(cript|tyle)>/g, '').replace(/<(link|title)(.|\s)*?\/(link|title)>/g,'');
                        return data;
    },                

    // can pass in standard $.ajax() parameters, not including error, complete, success, and url
    ajaxSettings: {   
                      dataType: 'html'
    },
    debug: false
  };


/*
 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
 *
 * @example $.cluetip.setup({
 *   insertionType: 'prependTo',
 *   insertionElement: '#container'
 * });
 * 
 * @property
 * @name $.cluetip.setup
 * @type Map
 * @cat Plugins/tooltip
 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
 *
 */
   
  var insertionType = 'appendTo', insertionElement = 'body';
  $.cluetip = {};
  $.cluetip.setup = function(options) {
    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
      insertionType = options.insertionType;
    }
    if (options && options.insertionElement) {
      insertionElement = options.insertionElement;
    }
  };
  
})(jQuery);
/* Copyright (c) 2007 Brandon Aaron (brandon.aaron@gmail.com || 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.
 *
 * Version: 1.0.2
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false;});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;$.livequery.run(q.id);return this;},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id);});return this;}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context||document;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this;};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el);});this.elements=[];this.stopped=true;},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn);});}else{nEls.each(function(){query.fn.apply(this);});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el);});}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run();}},pause:function(){$.livequery.running=false;},play:function(){$.livequery.running=true;$.livequery.run();},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r;}});},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);}else
$.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id);});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20);},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else
$.each($.livequery.queries,function(id){$.livequery.queries[id].stop();});}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove');$(function(){$.livequery.play();});var init=$.prototype.init;$.prototype.init=function(a,c){var r=init.apply(this,arguments);if(a&&a.selector)r.context=a.context,r.selector=a.selector;if(typeof a=='string')r.context=c||document,r.selector=a;return r;};$.prototype.init.prototype=$.prototype;})(jQuery);
jQuery(function() {
    
    jQuery.ajaxSetup(
        {
        url: '/?ajax=mRegistrantSearch',
        global: false,
        type: "POST",
        beforeSend: function () {
        	//alert("send ajax");
        }/*,
        dataType: "script"*/
        }
    );
     
    vSearch = new RegistrantSearch();
    vUserMessaging = new UserMessaging();
});
function RegistrantSearch() {
    
    if (!RegistrantSearch.instance) {
        RegistrantSearch.instance = this;
    }
    instanceRS = this;
    return RegistrantSearch.instance;
}

RegistrantSearch.prototype = {
 
	andTerms: null,
	noneTerms: null,
	recordCollection: "current",	//current or historical only
	
	/***********GETTERS************/
	getRecordCount: function (all,not,partialView,timePeriod) {	
				
		instanceRS.andTerms = all;
		instanceRS.noneTerms = not;
		instanceRS.recordCollection = timePeriod;

		jQuery.ajax({
			data: "call=getRecordCount&args[0]=" + instanceRS.recordCollection + "&" + instanceRS.andTerms + "&" + instanceRS.noneTerms,
	        dataType: "json",
			beforeSend: function() 
	        {
	        	UserMessaging.instance.showAjaxLoading('search');
	        },	
	        complete: function() 
	        {
	        	UserMessaging.instance.hideAjaxLoading('search');
	        },        
	        success: function(result)
	        {
	        	instanceRS.getDetails(result, partialView);
	        },
	        error: function()
	        {
	        	return UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'main-message',
					'error',
					'Registrant Search is temporarily unavailable',
					'This service is temporarily unavailable, please try checking back soon.'
				);
	        }
	    });	
	},
	getDetails: function (resultingRecords, partialView) {
		UserMessaging.instance.hidePageMessageAll("reg-search-tab-contents");
		var maxUniqueDomains = 100000;
		var maxTotalRecords = 5000000;

		var unique = resultingRecords.unique;
		var total = resultingRecords.total;		
		var c_unique = resultingRecords.current_unique;
		var c_total = resultingRecords.current_total;		
		var h_unique = resultingRecords.historical_unique;
		var h_total = resultingRecords.historical_total;
		
		if(unique <= 0) {			

			if(!partialView) {
				UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'main-message',
					'error',
					'There are no results from which to build a report',
					'Your search has not yielded any results. Please broaden your search below.'
				);	
			}
			
			return UserMessaging.instance.showPageMessage(
				'reg-search-tab-contents',
				'button-message',
				'red',
				'',
				'No results found. Please broaden your search criteria.'
			);	
				
		} else if(unique == '') {
		
			return UserMessaging.instance.showPageMessage(
				'reg-search-tab-contents',
				'button-message',
				'green',
				'',
				'We have found over ' + addCommas(maxUniqueDomains) + ' domains with over ' + addCommas(maxTotalRecords) + ' Whois records matching '+
				'your search criteria. Reports are limited to ' + addCommas(maxTotalRecords) + ' results. Please narrow your search.'
			);
		
		} else if(unique > 0 && unique < maxUniqueDomains) {

			if(!partialView) {	
				instanceRS.loadNewSearchTabReportPreview();
			}
						
			if(instanceRS.recordCollection == "current"){
				return UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'button-message',
					'green',
					'',
					'There are ' + addCommas(resultingRecords.current_unique) + ' domains with registrant information matching your current search criteria.<br /> '+
					'Expanding your search to include historical records will add ' + addCommas(resultingRecords.historical_unique) + ' domains to your results.'
				);				
			} else {
				return UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'button-message',
					'green',
					'',
					addCommas(unique) + ' domain names found with whois records matching your search criteria >>'
				);					
			}
					
		} else if(unique >= maxUniqueDomains) {
			
			if(!partialView) {
				UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'main-message',
					'error',
					'Your report is too large to process',
					'Your search has surpassed our results limit of ' + addCommas(maxTotalRecords) + ' for any given report. Please narrow your search below.'
				);	
			}	
					
			return UserMessaging.instance.showPageMessage(
				'reg-search-tab-contents',
				'button-message',
				'red',
				'',
				'We have found over ' + addCommas(maxUniqueDomains) + ' domains with over ' + addCommas(maxTotalRecords) + ' Whois records matching '+
				'your search criteria. Reports are limited to ' + addCommas(maxTotalRecords) + ' results. Please narrow your search.'
			);	
	
		}
		
	},
	/***********ORDER************/	
	orderThisReport: function (a1,a2,a3,a4,n1,n2,ucount,tp) {
	    
		var maxUniqueDomains = 100000;
		
		if(ucount < maxUniqueDomains) {
			jQuery.ajax({
		        data:"call=submitOrderForm&all[]=" + a1 + "&all[]=" + a2 + "&all[]=" + a3 + "&all[]=" + a4 + "&none[]=" + n1 + "&none[]=" + n2 + "&args[0]=" + ucount + "&args[1]=" + tp      
		        ,success: function(shoppingCartUrl) {
		        	if(shoppingCartUrl) {
		        		self.location = shoppingCartUrl;
		        	}	        	
		        }
		    });	
		}
	},
	/***********LOADING TABS************/	
	showActiveTabContent: function (tabId) {	
		instanceRS.hideInActiveTabContent();		
		return $(tabId).show();
	},	
	hideInActiveTabContent: function () {	
		return $("#reg-search-tab-contents").children(".tab-content-container").hide();
	},
	loadTabContainer: function (tabName,resultHtml) {
    	instanceRS.hideInActiveTabContent();
    	instanceRS.updateActiveTab('#'+tabName+'-view a');  
    	
    	if($("#active-"+tabName+"-content").length == 0){
    		$("#reg-search-tab-contents").prepend('<div id="active-'+tabName+'-content" class="tab-content-container">'+resultHtml+'</div>');
    	} else {
    		$("#active-"+tabName+"-content").html(resultHtml).show();
    	}		
	},
	loadNewSearchTab: function (loadNew) {	
		//id=active-new-content
		
		if($('#active-new-content').length == 0 || (loadNew)){
			jQuery.ajax({
		        data:"call=newSearchTab",	        
		        dataType: "html",
		        success: function(result)
		        {
		        	instanceRS.loadTabContainer('new',result);
					
					$('#search_form').livequery(function(){
						$("input#allOne").val("");
						$("input#allTwo").val("");
						$("input#allThree").val("");
						$("input#allFour").val("");
						
						$("input#noneOne").val("");
						$("input#noneTwo").val("");	

						$("input[@name=date-range]").eq(0).attr("checked",true); //current radio button
						$(this).unbind();

					});					
		        }
		    });			
		} else {
			instanceRS.updateActiveTab('#new-view a');
			instanceRS.showActiveTabContent('#active-new-content');
		}
	},
	loadPreFillSearchTab: function (a1,a2,a3,a4,n1,n2,tp,email) {	
		//id=active-new-content

		jQuery.ajax({
	        data:"call=newSearchTab&args[0]="+a1+"&args[1]="+email,
	        dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.loadTabContainer('new',result);     	
	        	
				$('#search_form').livequery(function(){
					$("input#allOne").val(a1);
					$("input#allTwo").val(a2);
					$("input#allThree").val(a3);
					$("input#allFour").val(a4);
					
					$("input#noneOne").val(n1);
					$("input#noneTwo").val(n2);	
					
					if(tp == "historical") {
						$("input[@name=date-range]").eq(1).attr("checked",true); //historical radio button
					} else {
						$("input[@name=date-range]").eq(0).attr("checked",true); //current radio button
					}
					
					
				});
	        }
	    });
	    
	},	
	loadNewSearchTabReportPreview: function () {
	    //id=active-new-content
	    
		jQuery.ajax({
			data: "call=newSearchTabReportPreview&args[0]=" + instanceRS.recordCollection + "&" + instanceRS.andTerms + "&" + instanceRS.noneTerms,
			beforeSend: function() 
	        {
	        	UserMessaging.instance.showAjaxLoading('retrieve');
	        },	        
			dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.loadTabContainer('new',result);
	        	UserMessaging.instance.hideAjaxLoading('retrieve');      	
	        	return false;
	        }
	    });
  
	},
/*	loadFreeSearchTab: function () {
		//id=active-free-content
		
		if($('#active-free-content').length == 0){
		    jQuery.ajax({
		        data:"call=freeSearchTab",
		        dataType: "html",
		        success: function(result)
		        {
					instanceRS.loadTabContainer('free',result);		        	        						
		        }
		    });
		} else {
			instanceRS.updateActiveTab('#free-view a');
			instanceRS.showActiveTabContent('#active-free-content');
		}
	},
	loadFreeSearchTabReport: function () {
	    jQuery.ajax({
	        data:"call=freeSearchTabReport",
	        dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.updateActiveTab('#free-view a');
				$("#reg-search-tab-contents").html(result);
	        }
	    });
	},
	loadFreeSearchTabWhoisFlyout: function () {
	    jQuery.ajax({
	        data:"call=freeSearchTabWhoisFlyout",
	        dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.updateActiveTab('#free-view a');
				$("#reg-search-tab-contents").html(result);
	        }
	    });
	},*/
	loadPricingTab: function () {
	    jQuery.ajax({
	        data:"call=pricingTab",
	        dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.loadTabContainer('price',result);
	        	return false;
	        }
	    });
	},
	loadMySearchTab: function () {
	    jQuery.ajax({
	        data:"call=mySearchTab",
	        dataType: "html",
	        success: function(result)
	        {
	        	instanceRS.loadTabContainer('my',result);
	        	return false;
	        }
	    });
	},	
	updateActiveTab: function (activeTab) {	
		$('.tab-strip').find('li').removeClass('tab-strip-active');
		$(activeTab).parent().addClass('tab-strip-active');	
	}
};

function UserMessaging() {

    if (!UserMessaging.instance) {
        UserMessaging.instance = this;
    }
    instanceUM = this;
    return UserMessaging.instance;
}

UserMessaging.prototype = {

	messageFrame: function (type, summary, description) {
		return '<div class="'+type+'">' +				
					'<div class="messaging-tl">' +
						'<div class="messaging-tr">' +
							'<div class="messaging-tc"></div>' +
						'</div>' +
					'</div>' +				
					'<div class="messaging-bwrap">' +
						'<div class="messaging-ml">' +
							'<div class="messaging-mr">' +
								'<div class="messaging-mc">' +
									'<div class="messaging-body">' +
										'<div class="messaging-summary">'+summary+'</div>' +
										'<div class="messaging-description">'+description+'</div>' +
									'</div>' +
								'</div>' +
							'</div>' +
						'</div>' +
						'<div class="messaging-bl">' +
							'<div class="messaging-br">' +
								'<div class="messaging-bc"></div>' +
							'</div>' +
						'</div>' +
					'</div>' +		
				'</div>';	
	},
    showPageMessage : function(pageId, messageClass, type, summary, description) {
    	if(messageClass == "main-message"){
    		return $("#"+pageId+" ."+messageClass).html(this.messageFrame(type, summary, description)).show();
    	} else if(messageClass == "button-message"){
    		return $("#"+pageId+" ."+messageClass).removeClass().addClass(messageClass).addClass(type).html(description).show();
    	} else {
    		return $("#"+pageId).html(this.messageFrame(type, summary, description)).show();
    	}
    },
    hidePageMessageAll : function(pageId) {
        this.hidePageMessageMain(pageId);
        this.hidePageMessageButton(pageId);
    },    
    hidePageMessageMain : function(pageId) {
        return $("#"+pageId +" .main-message").empty().hide();        
    },
    hidePageMessageButton : function(pageId) {
        return $("#"+pageId +" .button-message").empty().hide();
    },    
    showAjaxLoading : function(messageId) {
    	if(messageId == "retrieve"){instanceUM.hideAjaxLoading('search');}
    	return $("#ajax-loading-" + messageId).show();
    },    
    hideAjaxLoading : function(messageId) {
    	return $("#ajax-loading-" + messageId).hide();
    }    
}


/**** Flyouts ****/
jQuery(function() {
	 jQuery('a.load-local').livequery(function(){
		 jQuery(this).cluetip({
			local: true,
			activation: 'click',
			arrows: false
		});
	});	
	
	 jQuery('a.current-whois-flyout').livequery(function(){
		 jQuery(this).cluetip({
			local: false,
			activation: 'click',
			arrows: false
		});
	});		
});

/**** All ****/
/* Needed for initial loads when tab in url is set*/
function initUpdateActiveTab(activeTab){
	jQuery('.tab-strip').find('li').removeClass('tab-strip-active');
	jQuery(activeTab).parent().addClass('tab-strip-active');		
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/**** New Registration Tab ****/
function initSubmitSearchForm() {
	
	try{
		var partialView = true;		
		
		if(!(jQuery("#search_form input#allOne").val() == "" && 
			jQuery("#search_form input#allTwo").val() == "" && 
			jQuery("#search_form input#allThree").val() == "" && 
			jQuery("#search_form input#allFour").val() == ""))
		{
			clearInterval(searchInterval);
			submitSearchForm(partialView);
		}
		
	}catch(e){}
}

function finalSubmitSearchForm() {
	
	try{
		var partialView = false;
		submitSearchForm(partialView);		
	}catch(e){}
}

function submitSearchForm(partialView) {
	try{ 
		
		var a1 = jQuery("#search_form input#allOne").val();
		var a2 = jQuery("#search_form input#allTwo").val();
		var a3 = jQuery("#search_form input#allThree").val();
		var a4 = jQuery("#search_form input#allFour").val();
		
		var n1 = jQuery("#search_form input#noneOne").val();
		var n2 = jQuery("#search_form input#noneTwo").val();
		
		if(!partialView){
			//nothing to process
			if(a1=="" && a2=="" && a3=="" && a4=="") {
				return UserMessaging.instance.showPageMessage(
					'reg-search-tab-contents',
					'main-message',
					'error',
					'You have not entered a search term',
					'You must enter at least one search term below to perform a search. If you\'re not sure how to find '+
					'what you\'re looking for, read our <a rel="#flyout-search-tip" href="#flyout-search-tip" title="Search '+
					'Tips" class="load-local">search tips</a>, or you can <a href="http://support.domaintools.com/index.php?_m=tickets&_a=submit&step=1&departmentid=24">'+
					'create a support ticket</a> and we\'ll help you create a search query.'
				);
			}
		}
	
		if(!isOkaySearchTerm(a1)) return;
		if(!isOkaySearchTerm(a2)) return;	
		if(!isOkaySearchTerm(a3)) return;
		if(!isOkaySearchTerm(a4)) return;
		
		if(!isOkaySearchTerm(n1)) return;
		if(!isOkaySearchTerm(n2)) return;

		var a1 = "all[]=" + a1;
		var a2 = "&all[]=" + a2;
		var a3 = "&all[]=" + a3;
		var a4 = "&all[]=" + a4;
		
		var n1 = "none[]=" + n1;
		var n2 = "&none[]=" + n2;		
		
		if(jQuery("#search_form input[@name=date-range]:checked").val() == "current") {
			return RegistrantSearch.instance.getRecordCount(a1 + a2 + a3 + a4,n1 + n2,partialView,"current");
		} else if(jQuery("#search_form input[@name=date-range]:checked").val() == "historical") {
			return RegistrantSearch.instance.getRecordCount(a1 + a2 + a3 + a4,n1 + n2,partialView,"historical");
		}		
		
	} catch(e){
		return UserMessaging.instance.showPageMessage('reg-search-tab-contents','main-message','error','Form Submission','There was a problem submitting your form.  Please refresh the page and try again.');
	}
}

function isOkaySearchTerm(term) {
	if(!term) return true; // Not all of the term boxes were used
	// We need to get rid of whitespaces and evaluate whether or not the search results consist of a single quote
	term = term.replace(/^\s+|\s+$/g, '');
	if(term == '"' || term == "'") return false;
	return true;

}

/**** Search for FREE Tab ****/

/**** Pricing Tab ****/
function toggleFlyoutPriceTables(tableType,tableEvent) {
	
	if( jQuery(tableEvent).hasClass("expand")){
		
		//close price section if one is open already, before continuing
		if( jQuery("#flyout-content").find(".table-status").hasClass("collapse")) {
			 jQuery("#flyout-content").find(".table-status").removeClass("collapse").addClass("expand");
			 jQuery(".records-table").hide();
		}	
			
		 jQuery(tableEvent).removeClass("expand").addClass("collapse");
		 jQuery(tableEvent).parent().parent().next(".records-table").show();
	} else {
		 jQuery(tableEvent).removeClass("collapse").addClass("expand");
		 jQuery(tableEvent).parent().parent().next(".records-table").hide();
	}

}

/**** My Registrant Searches Tab ****/

