DOM = (document.getElementById) ? 1 : 0;
NS4 = (document.layers) ? 1 : 0;

function more(link,div,tr_text,fl_text, add_class)
{
    add_class = add_class || "false";
    if(($(link).html() == tr_text && tr_text != "") || !$(link).hasClass(add_class))
    {
       $(div).show();
       $(link).html(fl_text);
       if(add_class != "false")
       {
          $(link).addClass(add_class);
       }
    } else {
        $(div).hide();
        $(link).removeClass(add_class);
        $(link).html(tr_text);
    }
}
var e=function(i){return document.getElementById(i);}
function isAtMax(e, object, m){
    if(object.value.length > m)	{
        object.value = object.value.substr(0, m);
		showContent('/popup_window.html?type=informer&mess=' + encodeURI('Длинна поля должна быть не менее '+m+' символов!'));
    }
	var top = getOffsetTop(object);
	var left = getOffsetLeft(object)+object.offsetWidth;
    return overlib(m - object.value.length, WIDTH, 80, CAPTION, 'Symbols left', FIXX, left, FIXY, top);
}

function ucfirst (str, input)
{
    input = input || 0;
    str += '';
    var f = str.charAt(0).toUpperCase();
    if(input != 0)
    {
       $(input).val(f + str.substr(1));
       $(input).val(f + str.substr(1));
    }
    return f + str.substr(1);
}

// add to bookmap
function add_bookmap(a,url,title) {
    title = title || document.title;
    url = url || document.location;
    try {
         // Mozilla
         window.sidebar.addPanel(title, url, "");
    }
    catch (e) {
        try {
             // Internet Explorer
             //window.external.AddFavorite(url, title);
             eval("window.external.AddFa-vorite(url, title)".replace(/-/g,''));
        }
        catch (e) {
            // Opera
            if (typeof(opera) == "object") {
                a.rel = "sidebar";
                a.title = title;
                a.url = url;
                return true;
            }
            else {
                // Unknown
                showContent('/popup_window.html?type=informer&mess=' + encodeURI('Нажмите Ctrl-D чтобы добавить страницу в закладки'));
            }
        }
    }
    return false;
}


function timeLeft(objHour,objMinute,objSecond)
{
   var current_second = Math.round($(objSecond).html()-1);
   var current_minute = Math.round($(objMinute).html()) ;
   var current_hour   = Math.round($(objHour).html()) ;

   if( current_second <=0 )
   {
      current_second = 60;
      if((current_minute-1) <=0 )
      {
          current_minute = 60;

          if((current_hour-1) <=0)
          {
              current_hour =0;
          } else {
             current_hour--;
          }

      } else {
         current_minute--;
      }
   }

   // change values
   $(objSecond).html(current_second);
   $(objMinute).html(current_minute);
   $(objHour).html(current_hour);
}

function checkedAll(obj,parent)
{
   if($(obj).attr('checked'))
   {
      $('input[type=checkbox]',parent).attr('checked',true);
   } else {
      $('input[type=checkbox]',parent).removeAttr('checked');
   }
}
/**
 *   COOKIE
 */
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";
    document.cookie = c_name + "=" + c_value;
}

function checkCookie(cname,default_val) {

    default_val = default_val || " ";
    var cval = getCookie(cname);
    var res = " ";

    if (cval != null && cval != "") {
        res = cval;
    }
    else {
        cval = default_val;
        setCookie(cname, cval, 365);
    }
    return res;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

/**
 *  END COOKIE
 */

function removeByIndex(arr,arrayIndex){
    arr.splice(arrayIndex,1);
}

function in_array(elm, arr) {
    for(var i=0; i<arr.length; i++)
        if(elm == arr[i])
            return true;
    return false;
}

function explode( delimiter, string ) {
	    var emptyArray = { 0: '' };

	    if ( arguments.length != 2
	        || typeof arguments[0] == 'undefined'
	        || typeof arguments[1] == 'undefined' )
	    {
	        return null;
	    }

	    if ( delimiter === ''
	        || delimiter === false
	        || delimiter === null )
	    {
	        return false;
	    }

	    if ( typeof delimiter == 'function'
	        || typeof delimiter == 'object'
	        || typeof string == 'function'
	        || typeof string == 'object' )
	    {
	        return emptyArray;
	    }

	    if ( delimiter === true ) {
	        delimiter = '1';
	    }

    return string.toString().split ( delimiter.toString() );
}

function checkEmail(val) {
    var reg = /<[^>]*>/;
    if(val.match(reg))
    {
        return false;
    }
    reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
    if (!val.match(reg)) {
        return false;
    } else {
        return true;
    }
}


function reloadDiv(url,obj)
{
   obj = obj || '.reload';

   if(!$(obj).length)
   {
       $(this).parent().html('<div class="reload"></div>');
   }
   $(obj).show();
   $(obj).html('<img src="/images/ajax_load.gif" alt="ajax load" />');

   $.get(url,
           function(response){
               $(obj).html(response);
           })
}

function openNewWindow(url)
{
   var win_option = 'toolbar=0,titlebar=0,scrollbars=0,status=0,resizable=1,scrollbars=1,top=0,right=0,channelmode=yes, width=810,height=480';
   window.open(url, '',win_option,false);
}


function checkForm(form)
{
   // clear error div
   if($('.error').length)
   {
      $('.error').remove();
   }
   var email = $('input[name=email]',form);
   var error = 0;

   if(email.length)
   {
       if(!checkEmail(email.val()))
       {
          error = 1;
          showError(form,'Email введен не верно ');
       }
   }

   // check on empty fields
   var text_input = $('input[type=text]:not(.not_check)',form);
   var mess_about_empty_fields = 'Необходимо заполнить все поля формы';

   if(text_input.length)
   {
      text_input.each(
         function(){
             if(jQuery.trim($(this).val()) == '') {
                 error = 1;
                 showError(form,mess_about_empty_fields);
                 return false;
             }
         }
      );
   }

   // check textarea
  /* if(!error)
   {
      var textarea = $('textarea',form);
      if(textarea.length)
      {
          textarea.each(
             function(){
                 if(jQuery.trim($(this).val()) == ''){
                    error = 1;
                    showError(form,mess_about_empty_fields);
                    return false;
                 }
             }
          );
      }
   }*/

   // check select
   if(!error)
   {
      var select = $('select',form);
      if(select.length)
      {
         select.each(
            function(){
                if(jQuery.trim($(this).val()) == ''){
                    error = 1;
                    showError(form,mess_about_empty_fields);
                    return false;
                }
            }
         );
      }
   }


   if(error)
   {
       return false;
   } else {
       return true;
   }
}

function TargetDataForm(url, form)
{
    //$(target).html(response);
    var options = {
          dataType: 'html',
          success: function(response) {
              $.fn.colorbox({html:response, open:false});
          },
          error: function(error)  {
              $.fn.colorbox({html:error, open:true});
         }
	};
    $(form).ajaxForm(options);
 }
function showError(form, mess, errorClass) {
    // init
    errorClass = errorClass || 'error';
    mess = mess || 'Произошла ошибка приложения.';

    // show
    if ($('.' + errorClass).length) {
        if ($('.' + errorClass).html() != mess) {
            $('.' + errorClass).html($('.' + errorClass).html() + ';<br />' + mess);
        }

    } else {
        $(form).before('<div class="' + errorClass + '">' + mess + '</div>')
    }
}
function popUp (sURL, sName, x, y, dx, dy) {
	window.open(sURL, sName, 'left='+x+', top='+y+', width='+dx+', height='+dy+', scrollbars=1, resizable=1');
}

function SetValueAndSubmit(form_name,var_name,var_value){
    document.forms[form_name].elements[var_name].value=var_value;
    document.forms[form_name].submit();
}

function addEvent(obj, evType, fn){
 if (obj.addEventListener){
   obj.addEventListener(evType, fn, false);
   return true;
 } else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
 } else {
   return false;
 }
}

function ShowHide(id){
	var obj = e(id);
	if(obj.style.display != 'none')	{
		obj.style.display = 'none';
	}
	else {
		obj.style.display = '';
	}
}
/**
 *  Выводит в попап контет ответа по указаному url
 * @param url
 */
function showContent(url,content){
     content = content || '';

     if(content == '')
     {
         $.colorbox({html:'<div style="width:100px;height:100px;"><img src="/images/ajax_load.gif" alt="load"/></div>', open:true});
         $.post(
            url,
            function(request){
                if(!$('#load_container').length){
                    $('body').append('<div id="load_container" style="display:none">&nbsp;</div>');
                }

                $('#load_container').html('<div>'+request+'</div>');
                $.fn.colorbox({html:$('#load_container').html(), open:true});


                // delete old block
                $('#load_container').remove();
            }
         );
     } else {
         $.colorbox({html:content, open:true});

     }
}

function sentFrom(form,parent)
{
    parent = parent || '';
    if(parent != '')
    {
        $(parent).show();
        $(parent).html('<img src="/images/ajax_load.gif" alt="ajax load" />');
    }
    $.ajax({
       url: $(form).attr("action"),
       type: $(form).attr("method"),
       data: $(form).serialize(),
       success:function(response){
           if(parent != '')
           {
              $(parent).html(response);
           } else {
               $.fn.colorbox({html:response, open:true});
           }
       }
    });
}
function displaystyle(id, display) {
	var obj = e(id);
	obj.style.display = display;
}
var doCity=function(i,j){
document.search_form.states.value=i.innerHTML;
document.search_form.state.value=j;
e('citySelectPopup').style.display='none';
}
var doCateg=function(i,j){
document.search_form.jobcategories.value=i.innerHTML;
document.search_form.jobcategory.value=j;
e('catSelectPopup').style.display='none';
}

function openComments(url){
	window.open(url, "Link", 'width=700,height=400,left=100,top=100,resizable=1,scrollbars=1,menubar=0,status=0');
}
function setHover(el){
el.className='hover';
el.getElementsByTagName('ul')[0].style.width=el.clientWidth+'px';
}
function doHideComplainPopup(){
	$('#mask, .window').hide()
}
function doShowComplainPopup(id)
{
	$('.window .close').click(function (e) {   
	$('#mask, .window').hide();
	return false;
});        
$('#mask').click(function () {   
	$('.window').hide();   
	$(this).hide();
});            
   
	var maskHeight = $('#all').height()+40;   
	$('#mask').css({'width':'100%','height':maskHeight, 'left':0, 'top':0});   
	$('#mask').fadeIn(800);       
	$('#mask').fadeTo("slow",0.8);     
	var winW = $(window).width();
	var of = $('#cmpl_'+id).offset().top;
	of = of - $('#dialog').height()-40;
	var tp=document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;
	if(of <40+tp ) of=tp+40;
	$('#dialog').css('top',  of);
	$('#dialog').css('left', winW/2-$('#dialog').width()/2);   
	$('#dialog').fadeIn(1000);
}
var substlnk=function(e){
	if(typeof(e)=='string')e=document.getElementById(e);
	if(e && e.rel!=''){
		e.href=e.rel;
		e.rel='';
	}
}
var substlnkar=function(a){
	for(var i in a)substlnk(a[i]);
}

function toggleDivByClick(call_link,div,mess_hide, mess_show)
{
   mess_hide = mess_hide || "Развернуть ..";
   mess_show = mess_show || "Свернуть ..";
   if($(div).filter(':visible').length)
   {
      $(call_link).html(mess_hide);
   } else {
      $(call_link).html(mess_show);
   }
   $(div).toggle();
}

function CheckForLimitedCount2(obj, limit, error_message) {
var ar=obj.parentNode.parentNode.childNodes;
var j =0; for(i=0; i<ar.length; i++) if(ar[i].tagName=='LABEL'){
	var c=ar[i].childNodes;
	for(k=0;k<c.length;k++)
	if(typeof(c[k])!='undefined' && c[k].tagName=='INPUT' && c[k].checked) {
		j++; if(j>limit) obj.checked = false;
	}
}

if(j>limit)	showContent('/popup_window.html?type=informer&mess=' + encodeURI(error_message)); return false;
}
