var req_timeout = 30;
var redirect_after_logout = '/';
var is_ie = !!(window.attachEvent && !window.opera);
var className = (!is_ie) ? 'class' : 'className';

function _(s) {
  if (typeof(i18n)!='undefined' && i18n[s]) {
    return i18n[s];
  }
  return s;
}

/*
Ajax.Responders.register({
  onCreate : function() {showLoader(); },
  onComplete : function() {hideLoader();}
});
*/
function showLoader () {
	//$('load').style.display = 'block';
}

function hideLoader () {
	//$('load').style.display = 'none';
}

function displayMessage(msg) {
$('messenger').innerHTML = msg;
//Effect.Appear('messenger',{duration: 0.25, queue: 'end'});
$('messenger').style.display = 'block';
Effect.Fade('messenger',{duration: 4, queue: 'end'});
}

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
};

/*
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}
// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}
*/

function getSelectHtml(myList, listId, selectValue, className, emptyValue) {

var html = [];
var idx = 0;

if (className == undefined) {
  className = 'select_medium';
}

if (emptyValue == undefined) {
  emptyValue = "--- " + _('Select in the list') + " ---";
}

html[idx++] = "<select id='" + listId + "' name='" + listId + "' class='" + className + "'><option value=''>" + emptyValue + "</option><option value=''></option>";
myList.each(function(pair) {
  if (pair.key == selectValue) {
    html[idx++] = "<option value='" + pair.key + "' selected>" + pair.value + "</option>";
  } else {
    html[idx++] = "<option value='" + pair.key + "'>" + pair.value + "</option>";
  }
});
html[idx++] = "</select>";

return html.join("");
}
/*
function getMultiSelectHtml_old(myList, listId, size, selectValues) {

var html = [];
var idx = 0;

html[idx++] = "<select id='" + listId + "' name='" + listId + "' multiple size='" + size + "' class='select_multiple'><option value=''>--- " + _('Select in the list') + " ---</option><option value=''></option>";
myList.each(function(pair) {
  if (selectValues.contains(pair.key)) {
    html[idx++] = "<option value='" + pair.key + "' selected>" + pair.value + "</option>";
  } else {
    html[idx++] = "<option value='" + pair.key + "'>" + pair.value + "</option>";
  }
});
html[idx++] = "</select>";

return html.join("");
}
*/

function getMultiSelectHtml(myList, listId, selectValues) {

var html = [];
var idx = 0;

html[idx++] = "<div class='multicheckbox'>";

myList.each(function(pair) {
  html[idx++] = "<div class='multicheckbox_row'>";
  if (selectValues != null && selectValues.contains(pair.key)) {
    html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + pair.key + "' " + "name='" + listId + "[]' value='" + pair.key + "' checked /> " + pair.value + " ";
  } else {
    html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + pair.key + "' " + "name='" + listId + "[]' value='" + pair.key + "' /> " + pair.value + " ";
  }
  html[idx++] = "</div>";

});
html[idx++] = "</div>";

return html.join("");
}

function getMultiSelectHtmlValue(listId) {

  var val = '';

  $$('input[name=\"' + listId + '[]\"]').each(function(item) {
    if (item.checked) {
      if (val != '') {
        val += ',';
      }
      val+=item.value;
    }
  
  });

  return val;
}

function getMultiSelectHtmlNumericValue(listId) {

  var val = 0;

  $$('input[name=\"' + listId + '[]\"]').each(function(item) {
    if (item.checked) {
      if (item.value >= 1) {
        val+=Math.pow(2,item.value-1);
      }
    }
  
  });

  return val;
}


function getMultiCheckBoxHtml(myList, listId, selectValues) {

var html = [];
var idx = 0;

//var n = myList.keys().length;
//var i = Math.floor(n/2);

//html[idx++] = "<select id='" + listId + "' name='" + listId + "'><option value=''>--- " + _('Select in the list') + " ---</option><option value=''></option>";
myList.each(function(pair) {

  if (selectValues != null && selectValues.contains(pair.key)) {
    html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + pair.key + "' " + "name='" + listId + "[]' value='" + pair.key + "' checked /> " + pair.value + " ";

  } else {
    html[idx++] = "<input type=\"checkbox\" id='" + listId + "_" + pair.key + "' " + "name='" + listId + "[]' value='" + pair.key + "' /> " + pair.value + " ";
  }

/*
  if (pair.key == selectValue) {
    html[idx++] = "<option value='" + pair.key + "' selected>" + pair.value + "</option>";
  } else {
    html[idx++] = "<option value='" + pair.key + "'>" + pair.value + "</option>";
  }
*/  
});
//html[idx++] = "</select>";

return html.join("");
}

Array.prototype.contains = function (element) 
{
    for (var i = 0; i < this.length; i++) 
   {
      if (this[i] == element) 
      {
        return true;
      }
  }
  return false;
};

Array.prototype.toUrl = function (name) 
{
  var url = '';
   for (var i = 0; i < this.length; i++) 
   {
      if (url != '')
        url += '&';
      url += name + '[]=' + this[i];
  }
  return url;
};

function without(array,value) {
  var res = Array();
  for( var i = 0 ; i < array.length; i++)
  {
    if (array[i] != value) res.push(array[i]);
  }
  return res;
}

function without_key(array,key) {
  var res = Array();
  //alert(array.length + ' ' + key);
  for( var i = 0 ; i < array.length; i++)
  {
    if (i != key) res.push(array[i]);
  }
  return res;
}

function postForm(theform, url, custom_options) {

  new Ajax.Request(
    url,
    {
      method: 'post',
      parameters : theform.serialize(true),
      timeout    : req_timeout,
      onLoading : function(req) { showLoader();},
      onSuccess : function(req){
        hideLoader();
        var options = new Array();
        options['errorListDisplay'] = 'form';
        options['submitForm'] = false;
        options['successMessage'] = _('Your profile has been saved.');
        options['errorMessage'] =  _('The form contains errors. Please see above.');

        if (custom_options != undefined) {
          if (custom_options['successMessage'] != undefined) {
            options['successMessage'] = custom_options['successMessage'];
          }
          if (custom_options['disableAfterSubmit'] != undefined) {
            options['disableAfterSubmit'] = custom_options['disableAfterSubmit'];
          }
        }

        processResponseForm(req.responseText, theform, options);
       },
      onTimeout  : function(req){ alert('Error!\nThe request to the server timed out!\nStatus Text = '+req.statusText); },
      onError    : function(req){ alert('Error!\nStatus Text = '+req.statusText+'\nServer response = '+req.responseText);}
    }
  );
  return false;

}


//function processResponseForm(data, theform, errorList, errorStatus, message, popupDisplay, submitForm) {
function processResponseForm(data, theform, options) {

    if (options.errorListDisplay == 'form') {
      $("form_errors").innerHTML = "";
    }
    if (options.errorMessage != undefined) {
      $("form_status").innerHTML = "";
    }
    
    var json = data.evalJSON(true);
    
    if(typeof data == "error")
    {
        //console.warn("error!",args);
    }
    else
    {
        //var json = eval('(' + data + ')');
        var errors = $H(json.errors);
        
        errors.unset('REMOVE'); 
        if (errors.size() > 0) {
        
           if (options.errorListDisplay == 'form') {
            msg = '';
            msg += "<ul>";
            
            errors.each(function(pair) {
              msg += "<li>" + pair.value + "</li>";
            });
            msg += "</ul>";
            $("form_errors").innerHTML = msg;
            //$("form_status").innerHTML = '<p>' +  _('The registration form contains errors. See details above.') + '</p>';
          }
          else if (options.errorListDisplay == 'popup') {
            msg = '';
            errors.each(function(pair) {
              msg += pair.value + "<br/>";
            });
            //displayMessage(msg);
            alert(msg);
          }
        
          if (options.errorMessage != undefined) {
            $("form_status").innerHTML = '<p>' +  options['errorMessage'] + '</p>';
          }

        } else {
          if (options.submitForm == true) {
            theform.submit();
          } else {
          
            if (options.disableAfterSubmit == true) {
              theform.disable();
            }
            
            if (options.successMessage != undefined ) {
              $("form_status").innerHTML = '<p>' +  options['successMessage'] + '</p>';
            }
            
          }
        }
    }
}

  function validateForm(formid) {
    var theform = $(formid);
    $$('#' + formid + ' span.error').each(function(elt) {
      elt.remove();
    });
    if ($('error_message') != undefined) {
      $('error_message').remove();
    }
    $$('#' + formid + ' li.buttons button').each(function(elt) {
      elt.writeAttribute('disabled', 'disabled');
    });     
    theform.request({
      timeout    : req_timeout,
      onComplete: function(req){
        var data = req.responseText;
        var json = data.evalJSON(true);
        if(typeof data == "error")
        {
          console.warn("error!",args);
        }
        else
        {
          var errors = $H(json.errors);
          errors.unset('REMOVE'); 
          if (errors.size() > 0) {
            //$$('#' + formid + ' ol.forms')[0].insert({top: '<li id="error_message" class="errormsg"><label>' + _('The form contains errors. See details below.') + '</label></li>'});
            $(formid).insert({top: '<p id="error_message" class="errormsg">' + _('The form contains errors. See details below.') + '</p>'});
            errors.each(function(pair) {
              if (pair.value == _('Connection timeout')) {
                window.location=redirect_after_logout;
              }
              //$(pair.key).parentNode.insert({bottom: '<span class="error">' + pair.value + '</span>'});
              //$(pair.key).parentNode.innerHTML += '<span class="error">' + pair.value + '</span>';
              var error_span  = document.createElement('span');
              error_span.setAttribute(className, 'error');
              error_span.innerHTML = pair.value;
              $(pair.key).parentNode.appendChild(error_span);
            });
            $$('#' + formid + ' li.buttons button').each(function(elt) {
              elt.removeAttribute('disabled');
            });             
          } else {
            theform.submit();
          }
        }
      }
    });
  }

function discardElement(element) {
  var garbageBin = document.getElementById('IELeakGarbageBin');
  if (!garbageBin) {
    garbageBin = document.createElement('DIV');
    garbageBin.id = 'IELeakGarbageBin';
    garbageBin.style.display = 'none';
    document.body.appendChild(garbageBin);
  }
  // move the element to the garbage bin
  garbageBin.appendChild(element);
  garbageBin.innerHTML = '';
}

function preloadImages() {
	if (document.images) {
		for (var i = 0; i < preloadImages.arguments.length; i++) {
			(new Image()).src = preloadImages.arguments[i];
		}
	}
}

/*  
  function mousePosX(e) {
  	var posx = 0;
  	if (!e) var e = window.event;
  	if (e.pageX) 	{
  		posx = e.pageX;
  	}
  	else if (e.clientX) 	{
  		posx = e.clientX + document.body.scrollLeft
  			+ document.documentElement.scrollLeft;
  	}
          return posx;
  }
  
  function mousePosY(e) {
  	var posy = 0;
  	if (!e) var e = window.event;
  	if (e.pageY) 	{
  		posy = e.pageY;
  	}
  	else if (e.clientY) 	{
  		posy = e.clientY + document.body.scrollTop
  			+ document.documentElement.scrollTop;
  	}
          return posy;
  }
*/  
/*
	function showHide(id, styleDisplay, displayInline) {
		var node = document.getElementById(id);
		if(node) {
			if(styleDisplay) {
				node.style.display = styleDisplay;
			} else {
				if(node.style.display == 'none') {
					node.style.display = (displayInline ? 'inline' : 'block'); 
				} else {
					node.style.display = 'none';
				}
			}	
		}
	}
*/ 

  function toogle_button(btn, src1, src2)
  {
    if (btn.src.indexOf(src1) > -1)
    {
      btn.src = src2;
    }
    else
    {
      btn.src = src1;
    }
  }


function processErrors(json) {
  var errors = $H(json.errors);
  var connected = true;
  errors.unset('REMOVE');
  if (errors.size() > 0) {
      var msg = '';
      errors.each(function(pair) {
        if (pair.value == _('Connection timeout')) {
          window.location=redirect_after_logout;
          connected = false;
        }
        msg += pair.value + "\n";
      });
      if (connected) {
        alert(msg);
      }
      return false;
  }
  return true;
}

/* Mailbox */
function checkUncheckAllMessages(cb) {

  var checkbox_value = cb.checked ? 1 : 0;
  
  $$('#messages_form input[type="checkbox"]').each(function(elt) {
    elt.checked = checkbox_value;
  });
}

function sendMessage(theform) {

  var custom_options =  new Array();
  custom_options['successMessage'] = _('Your message has been sent');
  custom_options['disableAfterSubmit'] = true;
  
  var url = 'mymessages.php';
  postForm(theform, url, custom_options);

}

function setSelRange(inputEl, selStart, selEnd) { 
 if (inputEl.setSelectionRange) { 
  inputEl.focus(); 
  inputEl.setSelectionRange(selStart, selEnd); 
 } else if (inputEl.createTextRange) { 
  var range = inputEl.createTextRange(); 
  range.collapse(true); 
  range.moveEnd('character', selEnd); 
  range.moveStart('character', selStart); 
  range.select(); 
 } 
}

/* End Mailbox */