
function setPlaceholder(f, q, ph) {
    if (f === false) {
        var q = document.getElementById(q);
        if (!q) {
            return;
        }
    } else {
        var f = document.getElementById(f);
        if (!f || !f[q]) {
            return;
        }
        var q = f[q];
    }
    q.onfocus = function() {
        if (q.value == ph) {
            q.value = '';
        }
        if (q.value == '') {
            q.className = q.className.replace(/\bplaceholder\b/g, '');
        }
    }
    q.onblur = function() {
        if (q.value == '') {
            q.value = ph;
        }
        if (q.value == ph) {
            q.className += ' placeholder';
        }
    }
    if (f !== false) {
        f.onsubmit = function() {
            if (q.value == ph) {
                q.value = '';
            }
        }
    }
    q.onblur();
}

function checkAllTrigger(name, self)
{
    var ch_list = document.getElementsByName(name);
    var ch_cnt = 0;
    var all_ch = false;
    if (ch_list && ch_list.length > 0) {
        if (self.id == 'checkAllTrigger_'+name) {
            for (var i = 0, j = ch_list.length; i < j; i++) {
                ch_list[i].checked = self.checked;
                ch_cnt += ch_list[i].checked;
            }
            all_ch = self.checked;
        } else {
            for (var i = 0, j = ch_list.length; i < j; i++) {
                ch_cnt += ch_list[i].checked;
            }
            var trigger = document.getElementById('checkAllTrigger_'+name);
            if (trigger) {
                trigger.checked = (ch_cnt == ch_list.length);
            }
            all_ch = trigger.checked;
        }
    }
    return [all_ch, ch_cnt];
}

function setFocus(id)
{
    var el = document.getElementById(id);

    if (el) {
        el.focus();
    } else {
        el = document.getElementsByName(id);
        if (el.length > 0) {
            el[0].focus();
        }
    }
}


function redirect(url/*, new_win*/)
{
    var new_win = arguments[1] || 0;
    if ( ! new_win) {
        if (navigator.appName == 'Microsoft Internet Explorer') {
            var a = document.createElement('a');
            a.href = url;
            document.body.appendChild(a);
            a.click();
        } else {
            window.location.href = url;
        }
    } else {
        window.open(url);
    }
}


function popup(url, w, h)
{
    var x = parseInt(screen.availWidth / 2 - w / 2);
    var y = parseInt(screen.availHeight / 2 - h / 2) - 50;

    win = window.open(url, '', 'toolbar=no,location=no,directories=no,'+
        'status=yes,menubar=no,scrollbars=no,resizable=no,copyhistory=no,'+
        'width='+w+',height='+h+',top='+y+',left='+x);

    win.focus();

    return win;
}


function getKeyNum(ev)
{
    var keynum;
    var is_ctl = arguments[1] || 0;

    if(window.event) {     // IE
        keynum = window.event.keyCode;
    } else if(ev.which) {     // Netscape/Firefox/Opera
        keynum = ev.which;
    }

    if (isNaN(keynum) || (!is_ctl && keynum < 32)) {
        return -1;
    }

    return keynum;
}


function maxLength(field, ev)
{
    var maxChars = field.getAttribute ?
      parseInt(field.getAttribute('maxlength')) : '';

    var keynum = getKeyNum(ev);

    if (keynum == -1) {
        return true;
    }

    if(field.value.length >= maxChars) {
        return false;
    }
}


function setValue(id, value)
{
    var el = document.getElementById(id);

    if (el) {
        el.value = value;
    } else {
        el = document.getElementsByName(id);
        if (el.length > 0) {
            el[0].value = value;
        }
    }
}


/*
 * http://www.mredkj.com/tutorials/tutorial005.html
 * ================================================
 * (slightly modified)
 *
 */
function insertOptionBefore(list, text, value)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }

    if (list.selectedIndex >= 0) {
        var optNew = document.createElement('option');
        optNew.text = text;
        optNew.value = value;
        var optOld = list.options[list.selectedIndex];
        try {
            list.add(optNew, optOld); // standards compliant; doesn't work in IE
        }
        catch(ex) {
            list.add(optNew, list.selectedIndex); // IE only
        }
    }
}


function removeOptionSelected(list)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }
    var i;
    for (i = list.length - 1; i>=0; i--) {
        if (list.options[i].selected) {
            list.remove(i);
        }
    }
}


function appendOptionLast(list, text, value)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }
    var optNew = document.createElement('option');
    optNew.text = text;
    optNew.value = value;

    try {
        list.add(optNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
        list.add(optNew); // IE only
    }
}


function removeOptionLast(list)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }
    if (list.length > 0)
    {
        list.remove(list.length - 1);
    }
}


function removeAllOptions(list)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }
    list.length = 0;
}


function selectAllOptions(list)
{
    if (typeof(list) == 'string') {
        list = document.getElementById(list);
    }
    var i;
    for (i = 0; i < list.length; i++) {
        list[i].selected = true;
    }
}

/*
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
 * ========================================================================================
 */
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

/*
 * http://dklab.ru/chicken/nablas/38.html
 * ======================================
 */
function Dump(d,l) {
	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 + ": " + Dump(d[k],l + 1);
		}
		for (var i = 0; i < l - 1; i++) s += "  ";
		s += "}\n"
	} else {
		s += "" + d + "\n";
	}
	return s;
}

/*
 * from JS Calendar
 * ======================================
 */
function hideShowCovered(el) {

	function getAbsolutePos(el) {
		var r = { x: el.offsetLeft, y: el.offsetTop };
		if (el.offsetParent) {
			var tmp = getAbsolutePos(el.offsetParent);
			r.x += tmp.x;
			r.y += tmp.y;
		}
		return r;
	};

	function getStyleProp(obj, style){
		var value = obj.style[style];
		if (!value) {
			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
				value = document.defaultView.getComputedStyle(obj, "").getPropertyValue(style);
			} else if (obj.currentStyle) { // IE
				value = obj.currentStyle[style];
			} else {
				value = obj.style[style];
			}
		}
		return value;
	};

	var tags = new Array("applet", "iframe", "select");

	var p = getAbsolutePos(el);
	var EX1 = p.x;
	var EX2 = el.offsetWidth + EX1;
	var EY1 = p.y;
	var EY2 = el.offsetHeight + EY1;

	for (var k = tags.length; k > 0; ) {
		var ar = document.getElementsByTagName(tags[--k]);
		var cc = null;

		for (var i = ar.length; i > 0;) {
			cc = ar[--i];

			p = getAbsolutePos(cc);
			var CX1 = p.x;
			var CX2 = cc.offsetWidth + CX1;
			var CY1 = p.y;
			var CY2 = cc.offsetHeight + CY1;

			if ((el.style.display == 'none') || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getStyleProp(cc, "visibility");
				}
				cc.style.visibility = cc.__msh_save_visibility;
			} else {
				if (!cc.__msh_save_visibility) {
					cc.__msh_save_visibility = getStyleProp(cc, "visibility");
				}
				cc.style.visibility = "hidden";
			}
		}
	}
}


function addSuffixToFName(fname, suffix) {
    var fname = fname.split('.');
    if (fname.length == 1)
        return fname[0] + suffix;
    fname[fname.length - 2] += suffix;
    return fname.join('.');
}


$(document).ready(function() {

    // prepare form buttons
    $('.form_button').hover(function() {
        if($(this).attr('src').substr($(this).attr('src').length-7) != '_on.gif')
        {
            this.src = $(this).attr('src').substr(0, $(this).attr('src').length-4) + '_on.gif';
            $(this).attr('src', this.src);
        }
    }, function() {
        if($(this).attr('src').substr($(this).attr('src').length-7) == '_on.gif')
        {
            this.src = $(this).attr('src').substr(0, $(this).attr('src').length-7) + '.gif';
            $(this).attr('src', this.src);
        }
    });

    // prepare textareas
    $('textarea[maxlength]').keyup(function() {
        var maxChars = parseInt(this.getAttribute('maxlength'));
        if (isNaN(maxChars) || maxChars <= 0) {
            return;
        }
        if(this.value.length > maxChars) {
            this.value = this.value.substr(0, maxChars);
        }
    }).blur(function() {
        $(this).keyup();
    }).focus(function() {
        $(this).keyup();
    });

});

function rawurlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Michael Grier
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: rawurlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin%20van%20Zonneveld%21'
    // *     example 2: rawurlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: rawurlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    str = (str+'').toString();

    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A');
}

function array_diff () {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sanjoy Roy
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
    // *     returns 1: {0:'Kevin'}

    var arr1 = arguments[0], retArr = {};
    var k1 = '', i = 1, k = '', arr = {};

    arr1keys:
    for (k1 in arr1) {
        for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys;
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}

function array_values (input) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_values( {firstname: 'Kevin', surname: 'van Zonneveld'} );
    // *     returns 1: {0: 'Kevin', 1: 'van Zonneveld'}

    var tmp_arr = [], cnt = 0;
    var key = '';

    for ( key in input ){
        tmp_arr[cnt] = input[key];
        cnt++;
    }

    return tmp_arr;
}


function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}


// disables 'enter' key on text fields

function disableEnter(formID)
{
  x=document.getElementById(formID);
  if(!x)return;
  x=x.getElementsByTagName('*');
  for(a=0;a<x.length;a++)
    if(x[a].type=='text')
      x[a].onkeydown=function(event){event = event || window.event;if (event.keyCode == 13){return false;};};
}





function htmlspecialchars (string, quote_style, charset, double_encode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'
    var optTemp = 0,
        i = 0,
        noquotes = false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE': 1,
        'ENT_HTML_QUOTE_DOUBLE': 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE': 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i = 0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}



// jQuery.serializeJSON
(function( $ ){
    $.fn.serializeJSON=function() {
    var json = {};
    jQuery.map($(this).serializeArray(), function(n, i){
        json[n['name']] = n['value'];
    });
    return json;
};
})( jQuery );

