/* Key codes constant */
var KEYS = {BACKSPACE:8, TAB:9, RETURN:13, ESC:27, LEFT:37, UP:38, RIGHT:39, DOWN:40, DELETE:46, F5: 116,LF: 10,CR: 13};
var _defValues = {};

if ($.browser.msie) $(function () {
    $('input').focus(function () {$(this).addClass('txtfocus');}).blur(function () {$(this).removeClass('txtfocus');})
    $('textarea').focus(function () {$(this).addClass('txtfocus');}).blur(function () {$(this).removeClass('txtfocus');});
});

function log () {
	if ($.browser.chrome) return;
	if (!$.browser.safari && window['console'] !== undefined && console.log != undefined && $.isFunction(console.log)) console.log.apply(window, arguments);
	if ($.browser.opera && window['opera'] != undefined && opera.postError != undefined && $.isFunction(opera.postError)) opera.postError(arguments[0]);
}

function ge(id) {return document.getElementById(id);}
function hide(id) {if (typeof id == 'string') {id = '#'+id;}; $(id).css({display: 'none'});}
function show(id) {if (typeof id == 'string') {id = '#'+id;}; $(id).css({display: 'block'});}
function show_inline(id) {if (typeof id == 'string') {id = '#'+id;}; $(id).css({display: 'inline'});}
function ce(tag) {return document.createElement(tag);}
function str_replace (find, rep, text) {while (text.indexOf(find) != -1) {text = text.replace(find, rep);}; return text;}
function intval (val) {var integer = parseInt(val);if (isNaN(integer)) {return 0;} else {return integer;}}
function nl2br (text) {return text.replace(/\n/g, '<br />');}
function br2nl (text) {if (!text) return ''; return text.replace(/<br\s*\/?>/mig,"\n");}
function rehtsc(str) { return str.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&#39;/g,'\'').replace(/&#37;/g,'%');}
function htsc(str) { return str.replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/\'/g,'&#39;').replace(/%/g,'&#37;');}
function isValidEmail (email) {return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);}
function isValidUrl (url) {return (/^https?:\/\/[a-z0-9+$_-]+(\.[a-z0-9+$_-]+)*(\/[a-z0-9+$_\-].*)*\/?([a-z+&?$_.-][a-z0-9;:@\/&?%=+$_.-]*)?(#[a-z_.-][a-z0-9+$_.-]*)?$/i).test(url);}

function len(obj) {var length = 0; for (var i in obj) length++; return length;}
function clone(inpVar) {
  if (typeof(inpVar) == 'object' && (inpVar instanceof Array)) var outVar = [];
  else if (typeof(inpVar) == 'object') outVar = {};
  else return inpVar;
  for (var i in inpVar) {
    outVar[i] = clone(inpVar[i]);
  }
  return outVar;
}

function inArray (needle, hash, propertyName) {
  propertyName = propertyName || null;
  if (!hash) {return false;}
  for (var i in hash) {
  	if (propertyName) {if (hash[i][propertyName] == needle) {return i;}}
  	else {if (hash[i] == needle) {return i;}}
	}
  return -1;
}

function inArrayLower (needle, hash, propertyName) {
  needle = needle.toLowerCase();
  for (var i in hash) {
  	if (hash[i][propertyName].toLowerCase() == needle) {return i;}
  }
  return -1;
}

// Get browser window params
$(function () {window.pB = ge('pageBody');});
function getWnd() {
	var sz = {
		'bw': document.documentElement.clientWidth ? document.documentElement.clientWidth : (window.innerWidth ? window.innerWidth : document.body.offsetWidth),
		'bh': document.documentElement.clientHeight ? document.documentElement.clientHeight : (window.innerHeight ? window.innerHeight : document.body.offsetHeight),
		'w': Math.max(pB.scrollWidth, pB.offsetWidth),
		'h': Math.max(pB.scrollHeight, pB.offsetHeight),
		't': Math.max(document.documentElement.scrollTop, document.body.scrollTop, pB.scrollTop),
		'l': Math.max(document.documentElement.scrollLeft, document.body.scrollLeft, pB.scrollLeft)
	}
	if (sz.h < sz.bh) sz.h = sz.bh;
	return sz;
}

function cancelEvent(event) {
  if (!event) return;
  var e = event.originalEvent || event;
  if (e.preventDefault)
      e.preventDefault();
  if (e.stopPropagation)
      e.stopPropagation();
  e.cancelBubble = true;
  e.returnValue = false;
  return false;
}

function str_count(count, arr) {
  if (count != Math.floor(count)) {return arr[1];}
  count = intval(count);
  if (count == 1) {return arr[0];}
  if (count >= 2 && count <= 4) {return arr[1];}
  if (count == 0 || (count >= 5 && count <= 20)) {return arr[2];}

  var c = new String(count);
  cnt = c.substring(c.length-1);
  if (cnt == 1) { if (c.substring(c.length-2)==11) return arr[1]; else return arr[0]}
  if (cnt >= 2 && cnt <= 4) {return arr[1];}
  if (cnt == 0 || cnt >= 5) {return arr[2];}
}

function fade (notifyId, html, colorFrom, colorTo, time) {
	colorFrom = colorFrom || '#8D3500';
	colorTo = colorTo ||'#B3B39D';
	time = time || 3000;
	$('#' + notifyId).html(html).stop().css({'borderColor': colorFrom}).show().animate({'borderColor': colorTo}, time);
}

/* Events */
function getKey (event) {
  if(!event) event = window.event;
  if (!event) return -1;
  if(event.which)
    var key = event.which;
  else if(event.keyCode)
    var key = event.keyCode;

  return key;
}
function mouseButton (event) {
  if (event.which == null) {
     button = (event.button < 2) ? 1 : ((event.button == 4) ? 3 : 2);
  } else {
     button = (event.which < 2) ? 1 : ((event.which == 2) ? 3 : 2);
  }
  return button;
}
function mousePos (event)  {
  var x = event.pageX || (event.clientX + (de.scrollLeft || db.scrollLeft)) || 0;
  var y = event.pageY || (event.clientY + (de.scrollTop || db.scrollTop)) || 0;
  return {x:x, y:y};
}

function stopEvent(e) {e = e || window.event;if (!e) return;e.cancelBubble = true;if (e.stopPropagation) e.stopPropagation(); e.returnValue = false; return false;}


/* Elements position */
function offsetX (obj) {
  var x = 0;
  if (!document.layers) {
    var par = obj;
    var newX = 0;
    while(par) {
      newX = parseInt(par.offsetLeft)+(($.browser.msie && par != obj)?intval($(par).css('border-left-width')):0);
      if(par.offsetLeft) x += newX;
      par = par.offsetParent;
    }
  } else if (obj.x >= 0) x += obj.x;
  return x;
}

function offsetY (obj) {
  var y = 0;
  if(!document.layers) {
    var par = obj;
    var newY = 0;
    while(par) {
      newY = parseInt(par.offsetTop)+(($.browser.msie && par != obj)?intval($(par).css('border-top-width')):0);
      if(par.offsetTop) y += newY;
			par = par.offsetParent;
		}
	} else if (obj.y >= 0) y += obj.y;
	return y;
}
function getOffsetPos (obj) {return {x: offsetX(obj), y: offsetY(obj)};}


/* Input default values */
function setDefVal (objId, defVal, useColors) {
  useColors = useColors || false;
  _defValues[objId] = defVal;
  $('#'+objId).unbind('focus');
  $('#'+objId).unbind('blur');
  ge(objId).onfocus = function () {if (this.value == _defValues[this.id]) {this.value = ''; if (useColors) $(this).css('color','black');}};
  ge(objId).onblur = function () {if (this.value == '') {this.value = _defValues[this.id]; if (useColors) $(this).css('color','gray');}};
  ge(objId).onchange = function () {if (this.value == '') {this.value = _defValues[this.id]; if (useColors) $(this).css('color','gray');}};
  if (ge(objId).value == '' || ge(objId).value == defVal) {ge(objId).value = defVal; if (useColors) $('#' + objId).css('color','gray');}
}

function setVal (inpId, newVal) {
  newVal = rehtsc(newVal);
  var inp = typeof inpId == 'string' ? ge(inpId) : inpId;
  if (newVal == '' && _defValues[inpId] != undefined) {
    inp.value = _defValues[inpId];
  }
  else {
    inp.value = newVal;
  }
}
function getVal (inpId) {
  var inp = typeof inpId == 'string' ? ge(inpId) : inpId;
  if (!inp) return '';
  if (_defValues[inpId] != undefined && inp.value == _defValues[inpId]) {
    return '';
  }
  else {
    return inp.value;
  }
}

/* Currency helpers */
function getMoney(currency_id, pay_type, from_sum, to_sum) {
  var pay_text = "";
  pay_type = intval(pay_type);
  currency_id = intval(currency_id);
  switch (pay_type) {
    case 3: pay_text = l_discussedAtInterview; break;
    case 1: pay_text = from_sum;
    if (from_sum && currency_id)
      pay_text += ' '+str_count(from_sum, currencyTypesCases[currency_id-1]); break;
    case 2:
      if (from_sum) pay_text = l_from + ' ' + from_sum;
      if (to_sum) pay_text += (pay_text ? ' ':'') + l_to + ' ' + to_sum;
      if (to_sum && currency_id) pay_text += ' '+str_count(to_sum, currencyTypesCasesFrom[currency_id-1]);
      else if (from_sum && currency_id) pay_text += ' '+str_count(from_sum, currencyTypesCasesFrom[currency_id-1]);
      break;
  }
  return pay_text;
}

function getEuroDollars(currency_id, pay_type, from_sum, to_sum, ret) {
  ret = ret || 'compact';
  out = [];
  if (!currency_id) return (inArray(ret, ['compact', 'normal']) !== -1 ? "" : out);

  pay_type = intval(pay_type);
  currency_id = intval(currency_id);

  switch (pay_type) {
    case 1:
      if (currency_id != 5) out.push("$" + convert_money(from_sum, currency_id, 5));
      if (currency_id != 6) out.push("€" + convert_money(from_sum, currency_id, 6));
      break;
    case 2:
      if (currency_id != 5) {
        usd = [];
        if (from_sum) usd.push(convert_money(from_sum, currency_id, 5));
        if (to_sum) usd.push(convert_money(to_sum, currency_id, 5));
        out.push((usd.length ? "$" : "") + usd.join(ret == 'compact' ? '-' : ' - '));
      }
      if (currency_id != 6) {
        eur = [];
        if (from_sum) eur.push(convert_money(from_sum, currency_id, 6));
        if (to_sum) eur.push(convert_money(to_sum, currency_id, 6));
        out.push((eur.length ? "€" : "") + eur.join(ret == 'compact' ? '-' : ' - '));
      }
      break;
  }
  if (ret == 'compact') return out.join(', ');
  if (ret == 'normal') return out.join('<br />');
  else return out;
}

function convert_money(sum, currency1_id, currency2_id) {
  return Math.ceil(sum*currency_rates[currency1_id][currency2_id]/10)*10;
}

/* Windows helpers */
var _curShowedBox = false;
var _curShowedBoxParent = false;
var _curShowedBoxHideCb = false;
var hideCurrentBox = false;
function showBox (boxId, title, options) {
	if (!boxId) return false;
	title = title || '';
	if ($.isFunction(options)) {options = {'hideCb': options};}
	options = $.extend({'hideCb': false, 'progress': false}, options);

	if (options.progress) {
		title = title + ' <span style="display: none;" id="'+options.progress+'"><img src="/images/waits.gif" /></span>';
	}

	var wndBody = ge('wndBody');
	var wndTitle = ge('wndTitle');
	if (!wndBody) {
		var wndPageBG = ce('div');
		wndPageBG.id = 'wndPageBG';
		document.body.appendChild(wndPageBG);
		var wndContainer = ce('div');
		wndContainer.id = 'wndContainer';
		document.body.appendChild(wndContainer);
		var wndLayout = ce('div');
		wndLayout.id = 'wndLayout';
		wndContainer.appendChild(wndLayout);
		var wndHead = ce('h2');
		wndHead.id = 'wndHead';
		wndLayout.appendChild(wndHead);
		var wndCloseBtn = ce('a');
		$(wndCloseBtn).addClass('rightLink');
		wndCloseBtn.id = 'wndCloseBtn';
		$(wndCloseBtn).attr('href', '#');
		wndCloseBtn.onclick = function () {
			hide('wndPageBG');
			hide('wndContainer');
			$(_curShowedBox).css('display', 'none');
			_curShowedBoxParent.appendChild(_curShowedBox);
			_curShowedBoxParent = false;
			_curShowedBox = false;
			if (_curShowedBoxHideCb) _curShowedBoxHideCb();
			_curShowedBoxHideCb = false;
			return false;
		}
		hideCurrentBox = wndCloseBtn.onclick;
		wndHead.appendChild(wndCloseBtn);
		$(wndCloseBtn).text(l_close);
		var wndTitle = ce('span');
		$(wndTitle).addClass('title');
		wndTitle.id = 'wndTitle';
		wndHead.appendChild(wndTitle);
		var wndBody = ce('div');
		wndBody.id = 'wndBody';
		wndLayout.appendChild(wndBody);
	}
	var _box = ge(boxId);
	$(_box).css('display', 'block');
	elementParentsShow(_box);
	var maxHeight = _box.offsetHeight;
	var maxWidth = _box.offsetWidth;
	elementParentsHide(_box);
	$(_box).css('display', 'none');

	_curShowedBoxParent = _box.parentNode;
	_curShowedBox = _box;
	_curShowedBoxHideCb = options.hideCb;

	wndBody.appendChild(_box);
	$(wndTitle).html(title);

	var brWin = getWnd();

	$('#wndPageBG').css({'height': brWin.h, 'width': Math.max(brWin.bw, brWin.w)});
	show('wndPageBG');
	show('wndContainer');
	$(_box).css('display', 'block');

	$('#wndContainer').width(maxWidth+60);
	var top_y = (brWin.t + (brWin.bh - ge('wndContainer').offsetHeight)/2);
	$('#wndContainer').css({
		top: top_y,
		left: (brWin.l+(brWin.bw - ge('wndContainer').offsetWidth)/2)
	});
	try {
	  VK.callMethod('scrollWindow', top_y, 250);
	} catch (e) {};
  return false;
}

function showError (title, errorText, hideCb) {
	title = title || l_error;
	var errorTextDiv = ge('errorWndText');
	if (!errorTextDiv) {
		$(document.body).append('<div id="errorWnd" class="popUp"><div id="errorWndText"></div><div class="controlsContainer"><div class="controls"><input type="button" class="btn" value="Ок" onclick="return hideCurrentBox();"/></div></div></div>');
		errorTextDiv = ge('errorWndText');
	}
	$(errorTextDiv).html(errorText);
	return showBox('errorWnd', title, hideCb);
}

/* Textarea autosize */
function TAAutosize(textarea, options, fromTimeout) {
  if (textarea == null) return false;

	var w = $(textarea).width() || textarea.clientWidth;
	if ((w == undefined || !w || $.browser.msie) && !fromTimeout) {
		setTimeout(function () {TAAutosize(textarea, options, true)}, 200);
		return false;
	}

  // default options
  var defaults = {
    height: 0,
    minHeight: 0
  };
  // extend default options with user defined
  options = $.extend(defaults, options);

  var input = textarea, autosizeHelpers, helper;
  var oldValue, minHeight, maxHeight, fontSize;
  autosizeHelpers = ge('autosize_helpers');
  if (!autosizeHelpers) {
    autosizeHelpers = document.createElement('div');
    autosizeHelpers.id = 'autosize_helpers';
    autosizeHelpers.style.position = 'absolute';
    autosizeHelpers.style.left = '-1000px';
    autosizeHelpers.style.top = '-10000px';
    document.body.appendChild(autosizeHelpers);
  }
  helper = document.createElement('div');
  autosizeHelpers.appendChild(helper);

  minHeight = intval(options.minHeight);
  maxHeight = intval(options.height);
  if (!minHeight) {
    minHeight = $(input).height();
  }
  fontSize = intval($(input).css('fontSize'));
  input.style.overflow = 'hidden';

  // fix for hidden textareas
  helper.style.width = (w < 0 ? 0 : w) + 'px';
  helper.style.fontFamily = $(input).css('fontFamily');
  helper.style.fontSize = fontSize + 'px';
  helper.style.lineHeight = $(input).css('lineHeight');

  function updateSize(handleEvent) {
    return function(event) {
			event = event || window.event;
      var value = input.value;
      if (handleEvent) {
        if (getKey(event) == KEYS.RETURN && !event.ctrlKey && !event.altKey) {
          value += '\n';
        }
      }
      if (value == oldValue) {
        return;
      }
      oldValue = value;
      helper.innerHTML = htsc(value).replace(/\n/g, '<br>').replace(/<br>$/g, '<br>&nbsp;');

      var newHeight = helper.clientHeight + fontSize + 5;
      if (newHeight < minHeight) {
        newHeight = minHeight;
      }
      if (maxHeight > 0 && newHeight > maxHeight) {
        newHeight = maxHeight;
        input.style.overflow = 'auto';
      } else {
        input.style.overflow = 'hidden';
      }
      $(input).height(newHeight);
    }
  }

  input.onkeydown = updateSize(true);
  input.onkeypress = updateSize(true);
  input.onkeyup = updateSize(false);
  updateSize(false)();

  return false
}
/* Search helpers */
var skipToggleBox = false;
function toggleBox(id, name) {
  var box = ge(id);
  if(!box) return;
  if(skipToggleBox) { skipToggleBox = false; return; }

  $(box).toggleClass('boxClosed');
  $('.boxContent', box).toggle();
  if(name) $.get('/filter/toggle/'+name);
}

function clearFilters(filters) {
  if(!filters) return false;
  $.post('/filter/clear/multi', {data: $.toJSON({'clear': 1, 'filters': filters})}, function() {
    window.location.reload();
  });
  return false;
}

function serializeSearchForm(form_id, skipParseDdVal) {
  var form = ge(form_id);
  if(!form) return {};

  var result = {};

  $('input:not(div.ddc input)', form).each(function(i, inp) {
    var f = inp.id ? inp.id : inp.name;
    if(f) {
      var val = (_defValues[f] != undefined && inp.value == _defValues[f]) ? '' : inp.value;
      if(val) result[f] = val.replace('&', '%26');
    }
  });
  $('div.ddc input:not(:button)', form).each(function(i, inp) {
    if(dd[inp.id] != undefined && dd[inp.id].value.length)
      result[inp.id] = skipParseDdVal ? dd[inp.id].value : (dd[inp.id].limit > 1 ? $.map(dd[inp.id].value, function(o,i) {return o.v}) : dd[inp.id].value[0].v);
  });
  return result;
}

/**
 * Cookies
 **/
var _cookies;
function _initCookies() {
  _cookies = {};
  var ca = document.cookie.split(';');
  var re = /^[\s]*([^\s]+?)$/i;
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i].split("=");
    if(c.length == 2) {
     _cookies[c[0].match(re)[1]] = unescape(c[1].match(re) ? c[1].match(re)[1] : '');
    }
  }
}
function getCookie(name) {
  if(!_cookies) _initCookies();
  return _cookies[name];
}
function setCookie(name, value, days) {
  if(!_cookies) _initCookies();
  _cookies[name] = value;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  var domain = location.host.match(/[^.]+\.[^.]+$/);
  document.cookie = name+"="+escape(value)+expires+"; path=/"+(domain ? '; domain=.'+domain : '');
}


function showMap (address, company_title, params) {
    try {
        if (!YMaps) return false;
    } catch (e) {return false;}
    var mapEl = ge('blockMap');
    if (!mapEl) {
        mapEl = ce('div');
        mapEl.id = 'blockMap';
        document.body.appendChild(mapEl)
    }
    $(mapEl).css($.extend({
        'width': '500px',
        'height': '300px'
    }, params));
    var map = new YMaps.Map(mapEl);
    map.addControl(new YMaps.Zoom());
    map.enableScrollZoom();

    var geocoder = new YMaps.Geocoder(address);
    map.addOverlay(geocoder);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            var geoResult = this.get(0);
            geoResult.setBalloonContent("<b>" + company_title + "</b><br />" + address);
            map.addOverlay(geoResult);
            map.panTo(geoResult.getGeoPoint());
            map.setBounds(geoResult.getBounds());
            geoResult.openBalloon();
            showBox('blockMap', 'Карта');
        } else {
            showError("Ошибка", "Объектов с таким адресом не найдено.");
        }
    });

    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (error) {
        showError("Ошибка", "Объектов с таким адресом не найдено.");
    });
}