/**
 * Main js-functions library
 * 
 * @package    wsCat Jx
 * @version    1.0
 * @since      04.10.2008
 * @copyright  2004-2008 5Dev
 * @link       http://5dev.com
 */


// < Auto session code >
var sessionImg = new Image(16,16);

function auto_session()
{
    sessionImg.src = '/?auto_session=' + Math.random()*1000;
}

// </ Auto session code >

function stopError() 
{
    return true;
}

// window.onerror = stopError;

function OpenPage(pgSel, pgCnt)
{
    for (var pg = 1; pg <= pgCnt; pg++)
    {
        _v('pg_bl_' + pg).style.display = 'none';
        _v('pg_item_' + pg).className   = 'link';
    }

    _v('pg_item_' + pgSel).className   = 'clink';
    _v('pg_bl_' + pgSel).style.display = 'inline';
    _v('pg_bl_' + pgSel).style.width   = '440px';
}

function extCall(mod)
{
    if (self[mod])
        return;

    var jsSrc = '/j/' + mod.split('_').join('/');

    var head = document.getElementsByTagName('head')[0];

    var script  = document.createElement('script');
    script.id   = mod;
    script.type = 'text/javascript';
    script.src  = jsSrc;
    head.appendChild(script)

}

function objDump(d, l) 
{
    if (2 < l)
        return '';
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == 'object') 
    {
        s += typeof(d) + " {\n";
        for (var k in d) 
        {
            for (var i=0; i<l; i++) 
                s += "  ";

            s += k+": " + objDump(d[k],l+1);
        }
        for (var i=0; i<l-1; i++) 
            s += "  ";

        s += "}\n"
    } 
    else 
        s += '' + d + "\n";

    return s;
}

function findInSelect(obj, val, type)
{
    var cnt = obj.options.length;

    if (2 == type)
    {
        for (var i = 0; i < cnt; i++)
        {
            if (obj.options[i].text == val)
            {
                obj.options[i].selected = true;
                break;
            }
        }
    }
    else if (3 == type)
    {
        for (var i = 0; i < cnt; i++)
        {
            if (obj.options[i].value*1 == val*1)
            {
                obj.options[i].selected = true;
                break;
            }
        }
    }
    else
    {
        for (var i = 0; i < cnt; i++)
        {
            if (obj.options[i].value == val)
            {
                obj.options[i].selected = true;
                break;
            }
        }
    }
}

function adiv(res)
{
    return res ? 'block':'none';
}

function _v(id)
{
    return document.getElementById(id);
}

function in_array(needle, haystack)
{
    var len = haystack.length;
    for (var i = 0; i < len; i++)
    {
        if (needle == haystack[i])
            return true;
    }

    return false;
}

function in_arrayi(needle, haystack)
{
    var len = haystack.length;
    needle = needle.toLowerCase();
    for (var i = 0; i < len; i++)
    {
        if (needle == haystack[i].toLowerCase())
            return true;
    }

    return false;
}

function make_hidden(idnum)
{
   if (_v(idnum).style.display == 'none')
       _v(idnum).style.display = 'block';
   else
       _v(idnum).style.display = 'none';
}

function mhidden(idnum1,idnum2)
{
    _v(idnum1).style.display = 'none';
    _v(idnum2).style.display = 'block';
}

function spisokChange(klausel,spisok,nospisok)
{
    if (klausel.checked)
    {
        nospisok.disabled='';
        spisok.disabled='1';
    }
    else
    {
        nospisok.disabled='1';
        spisok.disabled='';
    }
}

function check_email(email)
{
    if (7 > email.length)
       return false;

    var zones = new Array(
            'ac','ad','ae','af','ag','ai','al','am','an','ao','aq','ar','as','at','au','aw','az',
            'ax','ba','bb','bd','be','bf','bg','bh','bi','bj','bm','bn','bo','br','bs','bt','bv',
            'bw','by','bz','ca','cc','cd','cf','cg','ch','ci','ck','cl','cm','cn','co','cr','cs',
            'cu','cv','cx','cy','cz','de','dj','dk','dm','do','dz','ec','ee','eg','eh','er','es',
            'et','eu','fi','fj','fk','fm','fo','fr','ga','gb','gd','ge','gf','gg','gh','gi','gl',
            'gm','gn','gp','gq','gr','gs','gt','gu','gw','gy','hk','hm','hn','hr','ht','hu','id',
            'ie','il','im','in','io','iq','ir','is','it','je','jm','jo','jp','ke','kg','kh','ki',
            'km','kn','kp','kr','kw','ky','kz','la','lb','lc','li','lk','lr','ls','lt','lu','lv',
            'ly','ma','mc','md','mg','mh','mk','ml','mm','mn','mo','mp','mq','mr','ms','mt','mu',
            'mv','mw','mx','my','mz','na','nc','ne','nf','ng','ni','nl','no','np','nr','nu','nz',
            'om','pa','pe','pf','pg','ph','pk','pl','pm','pn','pr','ps','pt','pw','py','qa','re',
            'ro','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sj','sk','sl','sm','sn','so',
            'sr','st','sv','sy','sz','tc','td','tf','tg','th','tj','tk','tl','tm','tn','to','tp',
            'tr','tt','tv','tw','tz','ua','ug','uk','um','us','uy','uz','va','vc','ve','vg','vi',
            'vn','vu','wf','ws','ye','yt','yu','za','zm','zw',
            'aero','biz','cat','com','coop','info','jobs','mobi','museum','name','net',
            'org','pro','travel','gov','edu','mil','int'
            );

    var regEmail = /^[\w-\.]+@([\w-]+\.)+([\w-]{2,4})$/;

    var myArr = regEmail.exec(email);

    if (null == myArr)
       return false;

    if (!in_arrayi(myArr[2], zones))
       return false;

    return true;
}

function isDigit(charCode){ return (charCode >= 48 && charCode <= 57)}
function isLat(charCode){ return ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122))}
function isRus(charCode){ return (charCode >= 1040 && charCode <= 1103)}
function filter(evt,set,exc,x) 
       { //set= 1 - digit 2 - lat 4 - rus; x=кроме set
    evt = (evt) ? evt : ((event) ? event : null);
    if (evt) {
        var charCode = (evt.charCode || evt.charCode == 0) ? evt.charCode :
            ((evt.keyCode) ? evt.keyCode : evt.which);
//alert(charCode);
        if (charCode > 13 && !x^(!(set&1 && isDigit(charCode)) && !(set&2 && isLat(charCode)) && !(set&4 && isRus(charCode)) && exc.indexOf(String.fromCharCode(charCode))==-1)) {
        if (evt.preventDefault) { evt.preventDefault(); } else { evt.returnValue = false; return false; }
        }
    }
}

function isNumeric(str)
{
  if (str.length == 0) return false;
  for (var i=0; i < str.length; i++)
     {
      var ch = str.substring(i, i+1);
      if ( ch < "0" || ch>"9" || str.length == null)  return false;
    }
  return true;
}

/**
 * Displays an confirmation box beforme to submit a "EXIT/DELETE" operations.
 * This function is called while clicking links
 *
 * @param   object   the link
 * @param   string   confirm message
 *
 * @return  boolean  whether to run the query or not
 */
function confirmLink(theLink, confirmMsg)
{
    // Confirmation is not required in the configuration file
    // or browser is Opera (crappy js implementation)
    if (confirmMsg == '' || typeof(window.opera) != 'undefined') {
        return true;
    }

    var is_confirmed = confirm(confirmMsg);
    if (is_confirmed) {
        theLink.href += '&is_js_confirmed=1';
    }

    return is_confirmed;
} // end of the 'confirmLink()' function

function selControl(obj)
{
   var i;
   var reg = /^check/;
   var result;
   for (i = 0; i < obj.form.elements.length; i++)
   {
       if (reg.test(obj.form.elements[i].name))
           obj.form.elements[i].checked = obj.checked;
   }
}
function wopen(url,name,w,h,r,s,st)
{
   var w=window.open(url,name,"width="+w+",height="+h+",resizable="+r+",toolbar=0,location=0,status="+st+",menubar=0,directories=0,scrollbars="+s);
}

function SimpleCheckForm(obj)
{
    obj.elements.submit.value    = 'Wait...';
    obj.elements.submit.disabled = true;
    return true;
}

function addCity(vvalue, vtext)
{
    fcity    = document.reg.elements['UserInfo[city_id]'];
    flength  = fcity.length;
    fcurrent = flength-1;

    document.reg.elements['UserInfo[city_id]'][fcurrent].selected = true;

    fcity.options[flength]        = new Option("Select other location...","XX_1_1");
    
    fcity.options[fcurrent].text  = vtext;
    fcity.options[fcurrent].value = vvalue;

    changeCity();
}

function UnsetUsername(obj)
{
    if (obj.form.elements['other_username'])
    {
        var cnt = obj.form.elements['other_username'].length;
        for (var i=0; i < cnt; i++)
        {
            obj.form.elements['other_username'][i].checked = false;
        }
    }
}

function UnsetPassword(obj)
{
    if (obj.form.elements['other_password'])
    {
        var cnt = obj.form.elements['other_password'].length;
        for (var i=0; i < cnt; i++)
        {
            obj.form.elements['other_password'][i].checked = false;
        }
    }
}

function showPass(passwd)
{
     document.reg.genpass.value      = 1;

    _v('pass1').style.visibility     = 'hidden';
    _v('pass1').style.display        = 'none';
    _v('textpass1').style.display    = 'block';
    _v('textpass1').style.visibility = 'visible';

    document.reg.elements['UserInfo[password1]'].value     = passwd;
    document.reg.elements['UserInfo[textpassword1]'].value = passwd;
   
    _v('pass2').style.visibility     = 'hidden';
    _v('pass2').style.display        = 'none';
    _v('textpass2').style.display    = 'block';
    _v('textpass2').style.visibility = 'visible';
   
    document.reg.elements['UserInfo[password2]'].value     = passwd;
    document.reg.elements['UserInfo[textpassword2]'].value = passwd;
}

function changeCity(type)
{
    sindex = document.reg.elements['UserInfo[city_id]'].selectedIndex;
    if (document.reg.elements['UserInfo[city_id]'][sindex].value == 'XX_1_1')
    {
        type = (type) ? type : 0;
         
        document.reg.elements['UserInfo[city_id]'][0].selected = true;

        wopen('/?mod=registration&action=select_city&type='+type,'EditCity',770,420);
    }
    
    // var iso2_cntr = document.reg.elements['UserInfo[city_id]'][sindex].value.split('_')[0];
}

function citySelectSubmit()
{
   if (window.opener)
   {
       found = false;
      
       if (0 == document.selectCountryForm.iso2_cntr.selectedIndex)
          return;

       ccountry = document.selectCountryForm.iso2_cntr[document.selectCountryForm.iso2_cntr.selectedIndex];
       
       if (document.selectRegionForm && 0 < document.selectRegionForm.subdiv_id.selectedIndex)
       {
           cregion = document.selectRegionForm.subdiv_id[document.selectRegionForm.subdiv_id.selectedIndex];
           if (document.selectCityForm && 0 < document.selectCityForm.city_id.selectedIndex)
           {
               ccity = document.selectCityForm.city_id[document.selectCityForm.city_id.selectedIndex];
               vvalue   = ccountry.value+'_'+cregion.value+'_'+ccity.value;

               if ('Main subdivision' == cregion.text)
                   vtext = ccity.text + ', ' + ccountry.text;
               else
                   vtext = ccity.text + ', ' + cregion.text;
           }
           else
           {
               vvalue = ccountry.value + '_'  + cregion.value + '_0';
               vtext  = cregion.text   + ', ' + ccountry.text;
           }
       }
       else
       {
           vvalue = ccountry.value + '_0_0';
           vtext  = ccountry.text;
       }

       fcity   = window.opener.document.reg.elements['UserInfo[city_id]'];
      
       flength = fcity.length;
      
       for (i=0;i<flength;i++)
       {
           if (fcity[i].value == vvalue)
           {
               fcity.selectedIndex=i;
               found=true;
               break;
           }
       }
      
       if (!found)
           window.opener.addCity(vvalue,vtext);
      
       window.close();
   }
}


function processWait(obj)
{
    // obj.disabled  = '1'; 
    obj.innerHTML = '<img src="/imgs/b_wait_l.gif" alt="" border="0" style="vertical-align: middle;" />  Wait ...   ';
}
