//===============================================================================
//## <AJAX>
var working;
var ct_base_url = "http://collegetreasure.com/";
var ct_ind_url = ct_base_url + 'index.php';
//===============================================================================
function getElementByMy(name) {
   if (document.getElementById) {
      curElement = document.getElementById(name);
   } else {
      curElement = document.all[name];
   }
   if (! curElement) {
      if (document.forms["frm"]) {
         curElement = document.frm[name];
      }
      if (! curElement) {
         if (document.forms["frm1"]) {
            curElement = document.frm1[name];
         }
      }
   }
   return curElement;
}
//========================================================================================
function FillSelect(sel, arr) {
   for (var i = 0; i < sel.options.length; i++) {
      sel.options[i] = null;
   }
   sel.options.count = 0;
   var tmp = '';
   for (var i = 0; i < arr.length; i=i+2) {
      var a=i/2;
      sel.options[a] = new Option(arr[i+1], arr[i]);
      tmp = tmp + i/2 + '|';
   }
}
//========================================================================================
function ParseResponse(str) {
   getElementByMy('site_keywords').innerHTML = str;
}
//========================================================================================
function majaxUniRequest(murl, mfnc, mdiv) {
   majaxGetUrl(murl, mfnc, mdiv);
}
//========================================================================================
function majaxPostUrl(xmlpage,data,callback,th)
{
   var xmlh = null;
   if (window.XMLHttpRequest) {
      xmlh = new XMLHttpRequest();
   } else {
      try {
         xmlh = new ActiveXObject('Msxml2.XMLHTTP');
      } catch(ex) {
         xmlh = new ActiveXObject('Microsoft.XMLHTTP');
      }
   }
   if(xmlh) {
      xmlh.open('post', xmlpage, true);

      xmlh.onreadystatechange = function(x) { if(xmlh.readyState==4) callback(xmlh.responseText, th); }

      xmlh.setRequestHeader('Accept-Charset', 'windows-1251');
      xmlh.setRequestHeader('Accept-Language','ru, en');
      xmlh.setRequestHeader('Connection', 'close');
      xmlh.setRequestHeader('Content-length', data.length); // Длинна отправляемых данных
      xmlh.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      r = xmlh.send(data);
   }
}
//========================================================================================
function majaxParseResponseAdv(responseText, th) {
   if (typeof(th['div']) != 'undefined') {
      te = getElementByMy(th['div']);
      if (te.type != undefined) {
         te.value = responseText;
      } else {
         te.innerHTML = responseText;
      }
   }
}
//========================================================================================
function majaxGetUrl(murl, mfnc, mdiv) {
   var http;

   http = get_http();
   if(! http){
      alert('err XMLHTTP err!')
   }

   // Запрос
   //alert(working + '|' +this.http);
   if (http) {   //(! working) &&
      //создаём запрос
      http.open("GET", murl, true);
      //прикрепляем к запросу функцию-обработчик
      //событий
      http.onreadystatechange = function() {
         // 4 – данные готовы для обработки
         if (http.readyState == 4) {
            working = false;
            //retrun http.responseText;

            if ((mfnc != '') && (mfnc != undefined)) {
               eval(mfnc + "(http.responseText);");
            } else {
               if ((mdiv != '') && (mdiv != undefined)) {
                  te = getElementByMy(mdiv);
                  if (te.type != undefined) {
                     //v(http.responseText);
                     te.value = http.responseText;
                  } else {
                     te.innerHTML = http.responseText;
                  }
               }
            }

         } else {
            //message: wait
         }
      }
      working = true;
      http.send(null);
   }
   if(!http){
      alert('err XMLHTTP объекта!')
   }
}
//========================================================================================
function get_http() {
  if (window.XMLHttpRequest) {
    //создание объекта для всех браузеров кроме IE
        requestObj = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      //для IE
        requestObj = new ActiveXObject("Msxml2.XMLHTTP");
        if (!requestObj) {
            requestObj = new ActiveXObject("Microsoft.XMLHTTP");
        };
    };
    return requestObj;
};
//========================================================================================
function StdJsonProcess(str) {

   //alert(str);

   var resp = eval('(' + str + ')');

   if (resp['div']) {
      cdiv = getElementByMy(resp['div']);
      cdiv.innerHTML = resp['cont'];
   }

}
//===============================================================================
function ChangePercent() {
   var re = /\d{1,2}/ig;
   $('#test_plan option:selected').each(function(){ //'#' + select +
      if ($('#percent').val().match(re) ) {
         $(this).val($(this).val().replace(re, $('#percent').val()));
         $(this).text($(this).val());
      }
   });
}
//========================================================================================
function moveUpItem(select){
   $('#' + select + ' option:selected').each(function(){ //'#' + select +
      $(this).insertBefore($(this).prev());
   });
}
//========================================================================================
function moveDownItem(select){
   $('#' + select + ' option:selected').each(function(){
      $(this).insertAfter($(this).next());
   });
}
//========================================================================================
//## <ENGINE>
//var lastzoekstr = 'J29dWTNVQV8TugOoCaLplUHwWPTgbWE8';
//========================================================================================
function FilterSelect(zoekstr, ListOfValues)
{

   zoekstr = zoekstr.toLowerCase();
   //if (zoekstr != lastzoekstr ) //&& zoekstr != ''
   //{
      //lastzoekstr = zoekstr;
      var LOV = ListOfValues;
      var aantal = LOV.options.length;
      var gevonden = 0;

      for (var x = 0; x < aantal; x++)
      {
         var CurrentRecordIndex = LOV.options[x].value;
         var CurrentRecordText  = LOV.options[x].text;
         var wasMatch;

         Match = (CurrentRecordText.toLowerCase().indexOf(zoekstr) >= 0);
         if (Match) wasMatch = 1;

         if ((zoekstr == '') || Match)
         {
            LOV.options[x].selected = true;
            LOV.options[x].style.display = 'block';
         } else {
            LOV.options[x].style.display = 'none';
         }
      }
   //}
   if (! wasMatch) {
      LOV.disabled = true;
      LOV.options[0].style.display = 'none';
   } else {
      LOV.disabled = false;
   }
}
//===============================================================================
function doNext(el)
{
   if (el.value.length < el.getAttribute('maxlength')) return;

   var f = el.form;
   var els = f.elements;
   var x, nextEl;
   for (var i=0, len=els.length; i<len; i++){
      x = els[i];
      if (el == x && (nextEl = els[i+1])){
         if (nextEl.focus) nextEl.focus();
      }
   }
}
//===============================================================================
function TestSubmit(obj) {
   if (window.confirm('Are you sure to submit results ?') == true) {
       //obj.disabled = 'true';
       //obj.form.submit();
       return true;
   }
   return false;
}
//===============================================================================
function CheckTestValue(obj) {
   if (
         (obj.value == 'a') || (obj.value == 'b') || (obj.value == 'c') || (obj.value == 'd')
         || (obj.value == 'e') || (obj.value == ' ') || (obj.value == '')
      )
   {
      doNext(obj);
      return true;
   } else {
      obj.value = '';
      obj.focus();
      alert('Allowed values are a..e or space. ');
      return false;
   }
   //alert(obj.value);
};
//========================================================================================
function FilterSelectChange(inp) {

   sv = inp.options[inp.selectedIndex].value;
   //v(sv);
   sselect = getElementByMy('schoolsh[]');

   sfelect = getElementByMy('schools[]');


   $('option[value='+sv+']', sselect).insertBefore($('option:first',sfelect)); //remove().

   text = $('option[value='+sv+']', sfelect).attr('selected', true);

}
//========================================================================================
function FilterChangeShowFiltered(filter_id, src_id, dst_id) {

   inp = getElementByMy(filter_id);

   sselect = getElementByMy(src_id);

   var k = sselect.options.length;
   c = 0;
   options = '';

   for (var i = 0; i < k; i++) {
      si = inp.value.toLowerCase();
      ss = sselect.options[i].text.toLowerCase();
      if (ss.indexOf(si) > -1)  {
         options = options + '<option value="' + sselect.options[i].value + '">' + sselect.options[i].text + '</option>'
         c++;
         if (c>10) break;
      }
   }
   $('#' + dst_id).html(options); //'select#filter_select'
}
//========================================================================================
function FilterSelectChangeAdv(inp, select_id, h_sel_id) {
   sv = inp.options[inp.selectedIndex].value;

   sselect = getElementByMy(select_id);

   shselect = getElementByMy(h_sel_id);

   $('option[value='+sv+']', shselect).insertBefore($('option:first',sselect));

   text = $('option[value='+sv+']', sselect).attr('selected', true);
}
//========================================================================================
function FilterChange(inp) {
   //v(inp.form.name);

   sselect = getElementByMy('schoolsh[]');

   var k = sselect.options.length;
   c = 0;
   options = '';
   for (var i = 0; i < k; i++) {
      si = inp.value.toLowerCase();
      ss = sselect.options[i].text.toLowerCase();
      if (ss.indexOf(si) > -1)  {
         options = options + '<option value="' + sselect.options[i].value + '">' + sselect.options[i].text + '</option>'
         c++;
         if (c>10) break;
      }
   }
   $('select#filter_select').html(options);
}
//========================================================================================
function HideNeed() {
   sel = getElementByMy('accept_type');
   need_id_in = getElementByMy('need_id');
   if (sel.selectedIndex == 0) {
      need_id_in.style.display = "none";
   } else {
      need_id_in.style.display = "inline";
   }
}
//========================================================================================
//## <OTHER FUNC>
//========================================================================================
function GetFormElementById(mform, en) {
   var frm_count = mform.elements.length;
   for (var i = 0; i < frm_count; i++) {
      v(mform.elements[i].id +'|'+en);
      if (en ==  mform.elements[i].id) {
         return mform.elements[i];
      }
   }
   return '';
}
//========================================================================================
function GetFormElement(mform, en) {
   var frm_count = mform.elements.length;
   var tarr = Array();
   for (var i = 0; i < frm_count; i++) {
      //v(mform.elements[i].name +'|'+en);
      if (en ==  mform.elements[i].name) {
         tarr.push(mform.elements[i]);
      }
   }
   return tarr;
}
//========================================================================================
function CheckAllCheckboxElements(mform, e) {
   err=1;

   for (a=0; a<130; a=a+2) {
      tn = e + a;
      tInp1 = document.getElementById(tn);
      if (tInp1) {
         if (typeof(tInp1) != 'undefined') {
            if (tInp1.checked == true) {
               err=0;
               break;
            }
         }
      }
   }
   return err;
}
//========================================================================================
function CheckFields(mform, ta) {
   if (typeof(ta) == 'undefined') return true;
   //alert('aa');
   d = ' | ';
   err = 0;
   for (var i=0;i<ta.length;i++) {
      var e = ta[i];

      tInpArr = GetFormElement(mform, e);

      for (var a=0;a<tInpArr.length;a++) {

         //tInp = mform.elements[e];

         tInp = tInpArr[a];

         // username not an input skip
         if (! tInp) {continue;}

         //alert(e +'|'+  tInp.name +'|'+ typeof(tInp) +'|'+ tInp.type +'|'+ tInp.checked +'|'+ tInp.value);

         if (tInp.disabled == true) err=1;

         if (typeof(tInp) != 'undefined') {
            if (tInp.type == 'checkbox') {
               if (tInp.name.indexOf('[]')>0) {
                  if (err!=1) {
                     err = CheckAllCheckboxElements(mform, e);
                  }
               } else {
                  if (tInp.checked == false) {
                     err=1;
                  }
               }
            } else {
               if (typeof(tInp.value) != 'undefined') {
                  if (tInp.value.length<1) {
                     err=1;
                  }
               } else {
                  if (err!=1) {
                     err = CheckAllCheckboxElements(mform, e);
                  }
               }
            }
         }
      }
   }

   if (err>0) {
      alert("Please fill all required (*) fields");
      return false;
   } else {
      return true;
   }
}
//========================================================================================
function SubmitAction(act, id) {
   document.frm.substep.value = act;
   document.frm.id.value = id;
   document.frm.submit();
}
//========================================================================================
function QstDel(link) {
   if (window.confirm('Delete item ?') == true) { // + link
      window.location=link;
   }
   return false;
}
//========================================================================================
function SubmitAction1(act, id) { //, id, cpos_null
   document.frm1.substep.value = act;
   document.frm1.id.value = id;
   if ((act=='del') && (window.confirm('Delete item ?') != true)) {
      return;
   }
   document.frm1.submit();
}
//========================================================================================
function SubmitActionFrm(frm, act, id) { //, id, cpos_null
   frm.substep.value = act;
   frm.id.value = id;
   if ((act=='del') && (window.confirm('Delete item ?') != true)) {
      return;
   }
   frm.submit();
}
//========================================================================================
function SubmitAction2(act, id) { //, id, cpos_null

   //v(getElementByMy('frm1'));

   document.frm1.substep.value = act;
   document.frm1.id.value = id;
   document.frm1.cpos.value = 0;
   if ((act=='del') && (window.confirm('Delete item ?') != true)) {
      return;
   }
   document.frm1.submit();
}
//========================================================================================
function CheckAll() {
   frm=document.frm1;
   for (var i=0;i<frm.elements.length;i++) {
      var e = frm.elements[i];
      if ((e.name != 'allbox') && (e.type=='checkbox')) {
         e.checked = frm.allbox.checked;
      }
   }
}
//========================================================================================
function ChangeContinent() {

   var SelectedContinent = frm.continent.options[frm.continent.selectedIndex].value;
   var oldSelectedCountry = frm.country.options[frm.country.selectedIndex].value;


   // (clear)
   var k = frm.country.options.length;
   for (var i = 0; i < k; i++) {
      frm.country.options[0] = null;
   }

   var result = '';
   var k=0;
   frm.country.options[k] = new Option('All', 'all');
   for (var i in ctr_cnt_h) {
      if ((ctr_cnt_h[i] == SelectedContinent) || (SelectedContinent == 'all')) {
         k++;
         frm.country.options[k] = new Option(i, i);
         if (oldSelectedCountry == i) frm.country.selectedIndex = k;
         result += i;
      }
   }
   //alert(result);
}
//========================================================================================
//## <DEBUG>
//========================================================================================
function v(str) {
   alert(str);
}
//========================================================================================
function c(str) {
   var debug = getElementByMy('debug');
   if (debug) {
     //debug.innerHTML += ' [' + str + '] ';
   }
}
//========================================================================================

