/* FILE: /js/FormControl.js */
FormControlPrototype = {

  focused: false,

  initialize: function( id, callback, report, onFailedCallback )
	{
		this.jsonHeader = 'text/x-json; charset=utf-8';
		this.owner = $( id );
    this.controls = new Array();
		this.callback = callback;
		this.onFailedCallback = onFailedCallback;
    this.tags = new Array('input', 'select', 'textarea');
    this.asyncTypeIFrame = false;

		if( report )
		  this.report = $(report).jControl;
    else
		  this.report = null;

		Event.observe( id, 'submit', this.send.bindAsEventListener(this) )
  },

	send: function( event )
	{
    if( this.asyncTypeIFrame )
		  return true;

		Event.stop(event);

		if( this.report != null )
		{
		  this.report.hide();
		  this.report.clear();
    }

    for (var i = 0; i < this.tags.length; i++)
		{
      var controls = this.owner.getElementsByTagName(this.tags[i]);

      for (var j = 0; j < controls.length; j++)
        controls[j].jControl.valid();
	  }


		this.owner.request({
      evalJS: true,
      onComplete: this.onComplete.bindAsEventListener(this)
    });

		return false;
  },

	onComplete: function( transport )
	{
    var response = transport.responseText.evalJSON(true);

		if( response.success )
		{
			if ( typeof(this.callback)=="function")
        this.callback();
		}
		else
		{
		 if ( typeof(this.onFailedCallback)=="function")
      this.onFailedCallback( transport.responseText.evalJSON(true) );

		 this.onFailed( response );
		}
	},

	onFailed: function( response )
	{
    if( this.report != null )
      this.report.show();


    for (var i = 0; i < response.errors.length; i++) {
      if ( $(response.errors[i].id) && typeof( $(response.errors[i].id).jControl ) == 'object' )
			{
        if( this.report != null && response.errors[i].msg != null )
          this.report.add( response.errors[i].msg );

        $(response.errors[i].id).jControl.invalidate();
			}
	 }
  },

	onLoad: function()
	{
     var elements = this.owner.getElements();

		  for (var i = 0; i < elements.length; i++) {
				if (elements[i].type != 'hidden' &&
				elements[i].type != 'submit' &&
				elements[i].type != 'select-one') {
			  try {
					$(elements[i]).activate();
					break;
				}
				catch (e) {}
			}
		}
	}
};

FormControl = Class.create( FormControlPrototype );

/* FILE: /js/InputControl.js */
InputControl = Class.create({

  initialize: function( id )
  {
	  this.owner = $( id );
    this.invalides = false;

    Event.observe( id, 'change', this.onChange.bindAsEventListener(this) );
	},

	onChange: function()
	{
   // this.valid();
  },

	valid: function()
	{
    this.owner.removeClassName( 'invalid' );
		tt_Hide();
		this.invalid = false;
	},

	invalidate: function()
	{
    this.owner.activate();
    this.owner.addClassName( 'invalid' );
		this.invalid = true;
	}
});
/* FILE: /js/ReportControl.js */
ReportControl = Class.create({

  initialize: function( name )
  {
    this.owner = $( name );
    this.list  = $( name + '-list' );
    this.isEmpty = true;
  },

  add: function( message )
  {
    this.isEmpty = false;
    this.list.update( this.list.innerHTML + '<li>' + message + '</li>' );
  },

  show: function()
  {
   this.owner.show();
  },

  hide: function()
  {
   this.owner.hide();
  },

  clear: function()
  {
   this.isEmpty = true;
   this.list.update('');
  }
});
/* FILE: /js/Helper.js */
Helper = {

  jumptvURL: "",
  jumptvSSLEnabled: null,
  languageCode: "",
  parnerCode: "",
  location: "",
  sessionCreateTime: "",
  
  getSecureJumpTVUrl: function()
  {
    if (this.jumptvSSLEnabled) 
      return this.jumptvURL.replace(/http:/, "https:");
    else 
      return this.jumptvURL.replace(/https:/, "http:");
  },
  
  getJumpTVUrl: function()
  {
    return this.jumptvURL.replace(/https:/, "http:");
  },
  
  getLang: function()
  {
    return this.languageCode;
  },
  
  getLocation: function()
  {
    return this.location;
  },
  
  getBrowser: function()
  {
  
    var str = navigator.userAgent;
    
    if (str.match(/Firefox\//)) 
      return 'FF';
    else 
      if (str.match(/Opera\//)) 
        return 'OP';
      else 
        if (str.match(/Safari\//)) 
          return 'SA';
        else 
          if (str.match(/Konqueror /)) 
            return 'KO';
          else 
            if (str.match(/MSIE /)) 
              return 'IE';
            else 
              return 'UNKNOWN';
  },
  
  
  getOS: function()
  {
    var str = navigator.userAgent;
    
    if (str.match(/Linux/)) 
      return 'LX';
    else 
      if (str.match(/Windows/)) 
        return 'MS';
      else 
        return 'UNKNOWN';
  },
  
  
  
  refresh: function(url)
  {
    var new_url = '';
    
    if (typeof url != 'undefined' && url) 
      new_url = url;
    else 
      new_url = document.location.href;
    
    new_url = new_url.replace(/#.*/, '');
    
    document.location.href = new_url;
  },
  
  
  getCookie: function(cookieName)
  {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") 
      return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) 
      ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
  },
  
  setCookie: function(name, value, expires, path, domain, secure)
  {
    var today = new Date();
    
    today.setTime(today.getTime());
    
    if (expires) {
      expires = expires * 1000 * 60 * 60 * 24;
    }
    
    var expires_date = new Date(today.getTime() + (expires));
    
    document.cookie = name + '=' + escape(value) +
    ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
    ((path) ? ';path=' + path : '') +
    ((domain) ? ';domain=' + domain : '') +
    ((secure) ? ';secure' : '');
  },
  
  addGetParam: function(main_url, param_name, param_value)
  {
    var param_separator = '?';
    if (main_url.indexOf('?') > 0) 
      param_separator = '&';
    
    if (typeof(param_value) == 'object' && param_value === null) 
      return main_url;
    
    return main_url + param_separator + param_name + "=" + encodeURIComponent(param_value);
  },
  
  calculatePopUpPosition: function(width, height, horizontal_align, vertical_align)
  {
    if (horizontal_align != 'center' || vertical_align != 'middle') 
      return;
    
    
    // Calculate windows size and position
    var window_params = {
      x: 0,
      y: 0,
      width: width,
      height: height
    }
    
    if (Helper.getBrowser() == 'IE') {
      window_params.x = window.screenLeft + window.document.documentElement.clientWidth / 2;
      window_params.y = window.screenTop + window.document.documentElement.clientHeight / 2;
    }
    else {
      window_params.x = window.screenX + window.innerWidth / 2 + (window.outerWidth - window.innerWidth - 4);
      window_params.y = window.screenY + window.innerHeight / 2 + (window.outerHeight - window.innerHeight - 25);
    }
    
    window_params.x = parseInt(window_params.x - window_params.width / 2);
    window_params.y = parseInt(window_params.y - window_params.height / 2);
    
    return window_params;
  },
  
  
  getPartnerCode: function()
  {
    return this.parnerCode;
  },
  
  
  waiter: function(element)
  {
    $(element).update('<img src="/img/waiter.gif" alt="waiter"/>');
  },
  
  getElementPosition: function(obj)
  {
    var curleft = 0;
    var curtop = 0;
    
    obj = $(obj);
    
    if (typeof obj.offsetParent !== "unknown" && obj.offsetParent) {
      curleft = obj.offsetLeft;
      curtop = obj.offsetTop;
      while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft - (obj.tagName != 'HTML' ? obj.scrollLeft : 0);
        curtop += obj.offsetTop - (obj.tagName != 'HTML' ? obj.scrollTop : 0);
      }
    }
    return {
      left: curleft,
      top: curtop
    };
  },
  
  riseClickEvent: function(object)
  {
    if (Prototype.Browser.IE) {
      object.fireEvent('onClick');
    }
    else {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
      object.dispatchEvent(evt);
    }
  },
  
  onButtonClick: function(event)
  {
    var target = Event.element(event);
    
    if (target.tagName != 'A' && target.tagName != 'BUTTON') {
      var tBody = target.parentNode.parentNode;
      
      var links = tBody.getElementsByTagName('a');
      
      if (typeof(links[0]) != "undefined") {
        this.riseClickEvent(links[0]);
        return;
      }
      
      var buttons = tBody.getElementsByTagName('button');
      
      if (typeof(buttons[0]) != "undefined") 
        this.riseClickEvent(buttons[0]);
    }
  },
  
  detectPlayerType: function()
  {
  	if(this.getCookie('wcq_player_type'))
		return;
	
	if(Player.is_wmp_plugin_installed())
		this.setCookie('wcq_player_type', 'application/x-ms-wmp', 30*24*3600*1000, '/');
  }  
};

/* FILE: /js/Search.js */
Search = {
  validateDays: function(message)
  {
    var retval = true;
    var elements = $$('#saved-searches-list .saved-search-days-field');
    elements.each(function(item){
      var value = item.getValue();
      if(value > 120 || value < 0)
      {
        alert(message);
        retval = false;
        throw $break;
      }
    });
    return retval;
  },
  resetFieldsForVinSearch: function()
  {
    var formFieldsList = ['make_id', 'category_id', 'state_id', 'model_id', 'color_id', 'type_id', 'start_year', 'end_year', 'odometer', 'location_first_line', 'savedsearch-name'];

		if( !$('search-form') )
		  return false;

		var elements = $A($('search-form').elements);
    elements.each(function(item){
      var matches = item.id.match(/^vehicle(model|seller)?-(.*)$/);
      if( matches !== null && formFieldsList.indexOf(matches[2]) !== -1)
        item.setValue(0);
      else
        if(formFieldsList.indexOf(item.id) !== -1)
          item.setValue('');
    });

    if( $('vehicle-nongm') )
      $('vehicle-nongm').checked = false;
  },
  AjaxFormFields : {
    prefilterForm: function(data, field)
    {
      var retval = {};
      switch(field)
      {
      case 'year':
        var key = 'data[Vehicle][start_year]';
        retval[key] = data[key];
        var key = 'data[Vehicle][end_year]';
        retval[key] = data[key];
      case 'model_id':
        var key = 'data[Vehicle][model_id]';
        retval[key] = data[key];
      case 'make_id':
        var key = 'data[VehicleModel][make_id]';
        retval[key] = data[key];
      case 'nonGM':
        var key = 'data[Vehicle][nonGM]';
        retval[key] = data[key];
      }
      return retval;
    },
    update: function(el)
    {
      var matches = el.name.match(/data\[(.*?)\]\[(.*?)\]/);
      if(matches)
      {
        var model = matches[1];
        var field = matches[2];
        this.updateRequest(model, field);
      }
    },
    updateRequest: function(model, field)
    {
      var url = '/search/getFormFieldsValues/';
      if(document.location.pathname.match(/\/ru\//))
        url = '/ru'+url;
      new Ajax.Request
      (url + model + '/' + field,
       {
         method: 'post',
         parameters: this.prefilterForm($('search-form').serialize(true), field),
         onSuccess: this.updateCallback.bind(this)
       }
      )
    },
    updateCallback: function(xhr)
    {
      var json = xhr.responseText.evalJSON(true);
      for(var id in json)
        this.updateSelectOptions($(id), json[id]);
    },
    updateSelectOptions: function(select, options)
    {
      select.options.length = 0;
      for(var i = 0; i < options.length; i++)
        select.options[i] = new Option(options[i].name, options[i].id);
      select.setValue(0);
    },
    updateYearFields: function(el)
    {
      var fieldName = el.name.match(/data\[.*?\]\[(.*?)\]/)[1];
      var startYearField = $('vehicle-start_year');
      var endYearField = $('vehicle-end_year');
      if( fieldName == 'start_year' )
      {
        if( el.value == 0 )
          endYearField.setValue(0);
        else
          if( endYearField.value == 0 )
            endYearField.setValue(el.value);
        else
          if( parseInt(endYearField.value) < parseInt(el.value))
            endYearField.setValue(el.value);
      }
      else
      {
      if( el.value == 0 )
        startYearField.setValue(0);
        else
          if( startYearField.value == 0 )
            startYearField.setValue(el.value);
        else
          if( parseInt(startYearField.value) > parseInt(el.value))
            startYearField.setValue(el.value);
      }
      this.updateRequest('Vehicle', 'year');
    }
  },

  simple: function( keywords )
  {
    $('search_keywords').value = keywords;
    $('simple-search').submit();
  },
  savedSearchSelected: function( )
  {
    var container = $('saved-searches-container');
    this.hideSavedSearch();
    var select = container.firstDescendant();
    $A(select.options).each(function(item){
      if(item.selected)
      {
        $('savedsearch-name').setValue(item.innerHTML);
        item.selected = false;
        throw $break;
      }
    });
    $('search-form').submit();
  },
  presubmit: function(action)
  {
    $('search-form').action = action;
    Pagination.resetPagination('search-form')
  },
  openSavedSearchByName: function(name, action)
  {
    $('savedsearch-name').setValue(name);
    this.presubmit(action);
    $('search-form').submit();
  },
  timeout: null,
  observeWindow: function()
  {
    Event.observe(document, 'mousemove', this.boundWindowMouseMove);
  },
  observeSavedSearch: function()
  {
    Event.observe($$('#saved-searches-container select')[0], 'mouseover', this.boundSelectMouseOver);
    Event.observe($$('#saved-searches-container select')[0], 'mouseout', this.boundSelectMouseOut);
  },
  windowMouseMove: function()
  {
    if(this.timeout === null)
      this.timeout = setTimeout(this.hideSavedSearch.bind(this), 1500);
  },
  hideSavedSearch: function()
  {
    $('saved-searches-container').hide();
    this.clearObservers();
    Event.stopObserving($$('#saved-searches-container select')[0], 'mouseover', this.boundSelectMouseOver);
    Event.stopObserving($$('#saved-searches-container select')[0], 'mouseout', this.boundSelectMouseOut);
  },
  toggleSavedSearchDisplay: function()
  {
    var element = $('saved-searches-container');
    if(!element.visible())
    {
      element.style.left = $('savedsearch-name').cumulativeOffset().left;
      element.show();
      this.observeWindow();
      this.observeSavedSearch();
    }
    else
      this.hideSavedSearch();
  },
  clearObservers: function()
  {
    Event.stopObserving(document, 'mousemove', this.boundWindowMouseMove);
    if(this.timeout !== null)
    {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
  },
  initObservers: function()
  {
    this.boundWindowMouseMove = this.windowMouseMove.bindAsEventListener(this);
    this.boundSelectMouseOver = this.clearObservers.bindAsEventListener(this);
    this.boundSelectMouseOut = this.observeWindow.bindAsEventListener(this);
  }
};
/* FILE: /js/Pagination.js */
Pagination = {
  gotoPage: function(page, formId)
  {
    var form = $(formId);
    form.page.value = page;
    form.submit();
  },
  sort: function(formId, fields, direction)
  {
    var form = $(formId);
    form.page.value = 1;
    form.order_fields.value = fields;
    form.order_direction.value = direction;
    form.submit();
  },
  resetPagination: function(formId)
  {
    var form = $(formId);
    if(typeof form.page !== 'undefined')
      $(form.page).setValue(1);
  }
}
/* FILE: /js/Bid.js */
Bid = {
  remove: function(id)
  {
      new Ajax.Request('/bids/remove_bid/' + id,
      {
        method:'get',        
        onSuccess: function(transport){        
        var response = transport.responseText.evalJSON(true);
        if(response.data.success == true) 
          Bid.markBidAsProcessing(id);  
        else
          alert(response.data.message);           
      }      
      });
  },
  
  buyNow: function(id)
  {
    new Ajax.Request('/bids/buy_now/' + id,
    {
        method:'get',        
        onSuccess: function(transport){
        var response = transport.responseText.evalJSON(true);
        if(response.data.success == true) 
          Bid.markBidAsProcessing(id);
        else
          alert(response.data.message);                                 
      }      
    });
  },
  
 bid: function(id)
 {
   var amount = $('amount_'+id).value;
   if(false == this.checkAmount(amount))
     return false;

    new Ajax.Request('/bids/bid/' + id + '/' + amount,
    {
        method:'get',        
        onSuccess: function(transport){
        var response = transport.responseText.evalJSON(true);
        if(response.data.success == true) 
          Bid.markBidAsProcessing(id); 
        else
          alert(response.data.message);                       
      }      
    });
 },
 
 autoBid: function(id)
 {
   var amount = $('amount_'+id).value;
   if(false == this.checkAmount(amount))
      return false;
      
  
    new Ajax.Request('/bids/auto_bid/' + id + '/' + amount,
    {
        method:'get',        
        onSuccess: function(transport){
        var response = transport.responseText.evalJSON(true);
        if(response.data.success == true) 
          Bid.markBidAsProcessing(id); 
        else
          alert(response.data.message);                       
      }      
    });    
 },
 
 checkAmount: function(amount)
 {
   if(amount != parseInt(amount))
   {
     alert('Amount should be integer.');
     return false;
   }
         
   if((amount % 100) != 0)
   {
     alert('Amounts must be entered in $100 increments ');
     return false;
   }
   
   return true;  
 },
  
 markBidAsProcessing: function(id)
 {
   $('default_image_'+id).src = '/img/searching.gif'; 
   $('default_image_'+id).width = 20;
   $('default_image_'+id).height = 20;   
   $('tr_'+id).onclick = function(){return false;}   
   $('a_remove_icon_'+id).onclick = function(){return false;};
   $('a_buy_now_icon_'+id).onclick = function(){return false;};     
 }
 
 
  
}
/* FILE: /js/UserForm.js */
UserForm = {


  showTmpPtoho: function (iframe)
  {
	  var content = iframe.contentWindow.document.body.innerHTML;

		if( !content.length )
	    return false;

		$('user-photo').value = content;
		$('image-preview').src = '/files/users_tmp_photos/' + content;
		$('image-preview-container').show();
		$('upload-control-container').hide();
  },

  showUploadControl: function()
	{
    $('upload-control-container').show();
		$('image-preview-container').hide();
  },

	showCancelControl: function()
  {
    $('cancel-control').show();
  },

	showPreviewControl: function()
	{
    $('upload-control-container').hide();
    $('image-preview-container').show();
  },

  handleSubmitClick: function()
  {
  },

  handleUploadPhotoClick: function()
  {
  },

	onLoadLogout: function( iframe ) {
		if( !iframe.src.match(/blank.html/) )
	   location.href='/';
  },
  
  onCopyFromPersonal: function()
  {
    $('user-holder_first_name').value = $('user-name').value;
    $('user-holder_last_name').value = $('user-surname').value;
  }
  

}