
String.prototype.stripHtml = function() {
    val = this;
    val = val.replace(/<[^>]+>/gim, "");
    val = val.replace(/<\/[^>]+>/gim, "");
    val = val.replace(/&nbsp;/gim, "");
    return val;
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}


String.prototype.isNumeric = function() {
    for(var i = 0; i < this.length; i++) 
        if ("0123456789.".indexOf(this.charAt(i)) == -1)
            return false;
    return true;

}


function Write(str) {
    document.write(str);
}

function showPhoto(src) {
    var wnd = window.open('/image.php?src='+src+'&mode=nodownload', "photo", "menubar=no,location=no,resizable=no,scrollbars=no,status=no,width=200,height=200");
    wnd.focus();
}

function makeArray(IntarrSize) {

  for (var n = 0; n < IntarrSize; n++)
    this[n] = "";

  return this;

}

function customSplit(strvalue, separator, arrayName) {
  var n = 0;

  if (separator.length != 0) {
    while (strvalue.indexOf(separator) != -1) {
      eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));");
      strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length,
          strvalue.length+1);
      n++;
    }
    eval("arr" + n + " = strvalue;");
    arraySize = n+1;
  }
  else {
    for (var x = 0; x < strvalue.length; x++) {
      eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";");
      n++;
    }
    arraySize = n;
  }

  eval(arrayName + " = new makeArray(arraySize);");

  for (var i = 0; i < arraySize; i++)
    eval(arrayName + "[" + i + "] = arr" + i + ";");

  return arraySize;
}

function isEmail(argvalue) {

  if (argvalue.indexOf(" ") != -1)
    return false;
  else if (argvalue.indexOf("@") == -1)
    return false;
  else if (argvalue.indexOf("@") == 0)
    return false;
  else if (argvalue.indexOf("@") == (argvalue.length-1))
    return false;

  // arrayString = argvalue.split("@"); (works only in netscape3 and above.)
  var retSize = customSplit(argvalue, "@", "arrayString");

  if (arrayString[1].indexOf(".") == -1)
    return false;
  else if (arrayString[1].indexOf(".") == 0)
    return false;
  else if (arrayString[1].charAt(arrayString[1].length-1) == ".") {
    return false;
  }

  return true;

}

function checkFormError(form) {
    for(k in window.formerrors) if(window.formerrors[k] == 1) return true;
    return false;
}

function enableFormPost(form) {
    return false;
    form.elements['ok'].disabled = checkFormError(form);
}

function changeElementsState(form, state) {
    return false;
    if(!state)
        form.elements['ok'].setAttribute("disabled", "disabled");
    else
        form.elements['ok'].removeAttribute("disabled");
}


function validateForm(obj, e) {
    if(!e) e = window.event;
    
    if(obj.tagName == "FORM") 
        var form = obj;
    else 
        var form = obj.form;
    
    for(el in form.elements) {
        if(form.elements[el] && form.elements[el].onblur != null && validateElement) {
            try {
                validateElement(form.elements[el], e);
            } catch(ex) {}
        }
    }
    
    try {
        validateCustomElements(form, e);
    } catch(ex) {}
    
    var isok = !checkFormError(form);
    if(!isok)
        alert('При заполнении формы были допущены ошибки, пожалуйста, исправьте их до отправления данных на сервер');
    
    return isok;
    
}

function HideStep(step) {
    var st = document.getElementById('idStep'+step).parentNode;
    var arClass = st.className.split(" ");
    arClass[arClass.length] = "hidden";
    st.className = arClass.join(" ");
    document.getElementById('idStickerStep'+window.currentStep).className = "";
}

function ShowStep(step) {
    var st = document.getElementById('idStep'+step).parentNode;
    var arClass = st.className.split(" ");
    var arNewClass = new Array();
    for(var i=0; i<arClass.length; i++) {
        if(arClass[i] != "hidden")
            arNewClass[arNewClass.length] = arClass[i];
    }
    st.className = arNewClass.join(" ");
    document.getElementById('idStickerStep'+window.currentStep).className = "active";
}

function NextStep(obj, numsteps) {
    if(numsteps == undefined)
        numsteps = 4;
    HideStep(window.currentStep);
    window.currentStep++;
    ShowStep(window.currentStep);
    
    if(window.currentStep == numsteps)
        document.getElementById('next').setAttribute("disabled", "disabled");
    else
        document.getElementById('next').removeAttribute("disabled");

    if(window.currentStep == 1)
        document.getElementById('prev').setAttribyte("disabled", "disabled");
    else
        document.getElementById('prev').removeAttribute("disabled");
        
    window.location="#steps";
}

function PrevStep(obj, numsteps) {
    if(numsteps == undefined)
        numsteps = 4;
    HideStep(window.currentStep);
    window.currentStep--;
    ShowStep(window.currentStep);
    
    if(window.currentStep == numsteps)
        document.getElementById('next').disabled="disabled";
    else                           
        document.getElementById('next').disabled="";

    if(window.currentStep == 1)
        document.getElementById('prev').disabled="disabled";
    else
        document.getElementById('prev').disabled="";
}

var ERROR = 'error_state';
var OK = 'ok_state';


function checkState(obj, state) {
    return obj.className.search(/ [^_|\s]*_state/) != -1;
}

function removeState(obj) {
    var clname = obj.className.replace(/[^_|\s]*_state/, '');
    obj.className = clname;
} 

function setState(obj, state) {
    removeState(obj);
    obj.className += ' '+state;
}

function setError(obj, message, omsg, aobjs){ 
    
    if(omsg == undefined)
        omsg = obj.form.elements[obj.name+'_message'];
    
    setState(obj, ERROR);
    setErrorMessage(omsg, message);
    
    if(aobjs != undefined)
        for(s in aobjs)
            setState(obj.form.elements[aobjs[s]], ERROR);
    
    window.formerrors[obj.name] = 1;
}

function clearError(obj, omsg, aobjs){ 
    if(omsg == undefined)
        omsg = obj.form.elements[obj.name+'_message'];
    else if(omsg.length)
        omsg[omsg.length] = obj.form.elements[obj.name+'_message'];

    setState(obj, OK);
    setErrorMessage(omsg, '');

    if(aobjs != undefined)
        for(s in aobjs)
            setState(obj.form.elements[aobjs[s]], OK);
    
    window.formerrors[obj.name] = 0;
}

function setErrorMessage(mobj, message) { 
    if(typeof(mobj) == 'Array') {
        for (o in mobj) mobj[o].value = message;
    }
    else
        mobj.value = message; 
}

function toggleLegend(name, obj) {
    var lc = findChild(obj.parentNode, 'obj.className.substr(0,2) == \'lc\'');
    if(lc.className.substr(3, 6) == 'hidden') {
        // it is hidden
        obj.childNodes[0].className = obj.childNodes[0].className.replace('lbh', 'lbs');
        obj.title = "Скрыть подсказку";
        return ShowLegend(name, obj);
    }
    else {
        // it is shown
        obj.childNodes[0].className = obj.childNodes[0].className.replace('lbs', 'lbh');
        obj.title = "Показать подсказку";
        return HideLegend(name, obj);
    }
    
    
}

function HideLegend(name, obj) {
    AjaxRequest("Functions.HideLegend", 
                name, 
                function(res, data) {}, 
                null);
    
    var lc = findChild(obj.parentNode, 'obj.className.substr(0,2) == \'lc\'');
    lc.className += ' hidden';
    return false;
}

function ShowLegend(name, obj) {
    AjaxRequest("Functions.ShowLegend", 
                name, 
                function(res, data) {}, 
                null);
                
    var lc = findChild(obj.parentNode, 'obj.className.substr(0,2) == \'lc\'');
    lc.className = lc.className.replace(' hidden', '');;
    return false;
}

function findChild(parent, request) {
    for(obj in parent.childNodes) {
        obj = parent.childNodes[obj];
        if(obj.nodeType == 1) {
            if(eval(request))
                return obj;
        }
    }
    return null;
}

function bin2hex(bin){
    var result = "";
    var temp = "";
    for(var i=0;i<bin.length;i++){
        var chr = bin.charCodeAt(i);
        if(chr>127){
            chr = encodeURIComponent(bin.charAt(i));
        }else{  
            chr = chr.toString(16); 
        }
        result += chr;
    } 

    for(var i=0;i<result.length;i++) {
        var chr = result.charAt(i);
        if(chr!='%'){
            temp+=chr;
        }
    } 
    return temp.toLowerCase();
} 
 
function _(id) {
    return document.getElementById(id);
}

function __(tagName) {
    return document.createElement(tagName.toUpperCase());
}



function MakeCharge(e, ticket) {
    AjaxRequest("Billing.ProcessTicket", e + ' ' + ticket, ChargeComplete, _('mbuy'));
    return false;
}

function ChargeComplete(res, data) {
    if(res.returnData.substr(0, 5) == "error") {
        var err = res.returnData.split(':');
        data.innerHTML = 'Система вернула ошибку: <strong>' + err[1] + '</strong><div class="error-message">' + err[2] + '</div>';
        // 'Произошла ошибка в процессе покупки, попробуйте перезайти в систему. В случае повторения ошибки, пожалуйста, свяжитесь с менеджером.' + '<br /><br />'
    }
    else {
        location.reload();
    }
    
    
}