
function check_any_selected( element, value ) {
    if ( ( !value.toString().search( /-1/ ) ) || ( value.toString() === '' )  ) {

        // we must clear all other selections
        for (i=0; i<element.options.length; i++) {
            if ( ( element.options[i].value != '-1' ) && ( element.options[i].value !== '' ) ) {
                element.options[i].selected = false;
            }
        }
    }
}

function get_email_addr( $to, $domain ) {
    return $to+'@'+$domain;
}

function display_email( $to, $domain ) {
    document.write( $to+'@'+$domain );
}

function generate_region( element, value ) {

    var value2 = String( value );
    var value3 = value2.replace( /,/g, "|" );

    var selected_val = element.options[element.selectedIndex].value;

    if ( ( value.toString().search( /-1/ ) ) && ( selected_val !== '' ) ) {

        var regions_div = document.getElementById('regions_select');

        if ( regions_div == undefined ) {
            regions_div = document.getElementById('regions_select_single');
        }

        if ( regions_div ) {
            regions_div.innerHTML = '<img src="http://www.totalrewardsjobs.co.uk/img/ajax-loader.gif" />';
            new Ajax.Request( 'http://www.totalrewardsjobs.co.uk/regions/regions_json/'+value3, {
                asynchronous: 1,
                onSuccess:
                    function(request){
                        var json_string = request.responseText;
                        var select = '<select>';
                        if ( typeof select_attribs != 'undefined' ) {
                            select = '<select '+select_attribs+'>';
                        }
                        eval( "var select_options = "+json_string+";" );
                        for ( variable in select_options ) {
                            select += '<option value="'+variable+'">'+select_options[variable]+'</option>';
                        }
                        select += '</select>';
                        regions_div.innerHTML = select;
                    }
            });
        }
    }
}

// Just for admin region using jquery because prototype affects the flash editor

function generate_region2( element, value, empty_start ) {

    var value2 = String( value );
    var value3 = value2.replace( /,/g, "|" );

    var selected_val = element.options[element.selectedIndex].value;

    if ( ( value.toString().search( /-1/ ) ) && ( selected_val !== '' ) ) {

        // get regions select
        var regions_div = document.getElementById('regions_select');

        if ( regions_div == undefined ) {
            // try single
            regions_div = document.getElementById('regions_select_single');
        }

        regions_div.innerHTML = '<img src="http://www.totalrewardsjobs.co.uk/img/ajax-loader.gif" />';

        $.get( 'http://www.totalrewardsjobs.co.uk/regions/regions_json/'+value3, function(data) {

            var json_string = data;
            var select = '<select>';

            if ( typeof select_attribs != 'undefined' ) {
                select = '<select '+select_attribs+'>';
            }

            // start empty
            if ( empty_start != '' ) {
                // select += '<option value="">Any</option>';
            }

            // Start item (predefined)

            if ( typeof start_items != 'undefined' ) {
                for ( variable in start_items ) {
                    select += '<option value="'+variable+'">'+start_items[variable]+'</option>';
                }
            }

            eval( "var select_options = "+json_string+";" );

            for ( variable in select_options ) {
                select += '<option value="'+variable+'">'+select_options[variable]+'</option>';
            }

            select += '</select>';

            regions_div.innerHTML = select;

        });

    }

}

// json parser
// from json.org with small modification
var cur_str_chr;

function json_parse(text) {

    var at = 0;
    var ch = ' ';

    function error(m) {
        throw {
            name: 'JSONError',
            message: m,
            at: at - 1,
            text: text
        };
    }

    function next() {
        ch = text.charAt(at);
        at += 1;
        return ch;
    }

    function white() {
        while (ch !== '' && ch <= ' ') {
            next();
        }
    }

    function str() {
        var i, s = '', t, u;

        if (ch == '\'' || ch == '"') { //change " to ' for python
            cur_str_chr = ch;
outer:          while (next()) {
                if (ch == cur_str_chr) {
                    next();
                    return s;
                } else if (ch == '\\') {
                    switch (next()) {
                    case 'b':
                        s += '\b';
                        break;
                    case 'f':
                        s += '\f';
                        break;
                    case 'n':
                        s += '\n';
                        break;
                    case 'r':
                        s += '\r';
                        break;
                    case 't':
                        s += '\t';
                        break;
                    case 'u':
                        u = 0;
                        for (i = 0; i < 4; i += 1) {
                            t = parseInt(next(), 16);
                            if (!isFinite(t)) {
                                break outer;
                            }
                            u = u * 16 + t;
                        }
                        s += String.fromCharCode(u);
                        break;
                    default:
                        s += ch;
                    }
                } else {
                    s += ch;
                }
            }
        }
        error("Bad string");
    }

    function arr() {
        var a = [];

        if (ch == '[') {
            next();
            white();
            if (ch == ']') {
                next();
                return a;
            }
            while (ch) {
                a.push(val());
                white();
                if (ch == ']') {
                    next();
                    return a;
                } else if (ch != ',') {
                    break;
                }
                next();
                white();
            }
        }
        error("Bad array");
    }

    function obj() {
        var k, o = {};

        if (ch == '{') {
            next();
            white();
            if (ch == '}') {
                next();
                return o;
            }
            while (ch) {
                k = str();
                white();
                if (ch != ':') {
                    break;
                }
                next();
                o[k] = val();
                white();
                if (ch == '}') {
                    next();
                    return o;
                } else if (ch != ',') {
                    break;
                }
                next();
                white();
            }
        }
        error("Bad object");
    }

    function num() {
        var n = '', v;
        if (ch == '-') {
            n = '-';
            next();
        }
        while (ch >= '0' && ch <= '9') {
            n += ch;
            next();
        }
        if (ch == '.') {
            n += '.';
            while (next() && ch >= '0' && ch <= '9') {
                n += ch;
            }
        }
        if (ch == 'e' || ch == 'E') {
            n += 'e';
            next();
            if (ch == '-' || ch == '+') {
                n += ch;
                next();
            }
            while (ch >= '0' && ch <= '9') {
                n += ch;
                next();
            }
        }
        if (ch == 'L')next();//for python long
        v = +n;
        if (!isFinite(v)) {
            error("Bad number");
        } else {
            return v;
        }
    }

    function word() {
        switch (ch) {
            case 't':
                if (next() == 'r' && next() == 'u' && next() == 'e') {
                    next();
                    return true;
                }
                break;
            case 'f':
                if (next() == 'a' && next() == 'l' && next() == 's' &&
                        next() == 'e') {
                    next();
                    return false;
                }
                break;
            case 'n':
                if (next() == 'u' && next() == 'l' && next() == 'l') {
                    next();
                    return null;
                }
                break;
        }
        error("Syntax error");
    }

    function val() {
        white();
        switch (ch) {
            case '{':
                return obj();
            case '[':
                return arr();
            case '\'':
            case '"':
                return str();
            case '-':
                return num();
            default:
                return ch >= '0' && ch <= '9' ? num() : word();
        }
    }

    return val();
}

// for renew record button
function renew_record( ele ) {
    $( ele ).value = '';
    return true;
}

// move selected options up
function moveOptionsUp()
{
	frm = document.forms["cat_order_form"] ;
	aOptions =frm.elements["cat_position"].options ;

	bSwapEnabled = false ;
	for( i=0; i<aOptions.length; i++ )
	{
		if ( !aOptions[i].selected )
			bSwapEnabled = true ;
		else if ( aOptions[i].selected && bSwapEnabled )
			swapOptions( aOptions, i, i-1 ) ;
	}

	refreshOptionList() ;
}

// move selected options down
function moveOptionsDown()
{
	frm = document.forms["cat_order_form"] ;
	aOptions = frm.elements["cat_position"].options ;

	bSwapEnabled = false ;
	for( i=(aOptions.length-1); i>=0; i-- )
	{
		if ( !aOptions[i].selected )
			bSwapEnabled = true ;
		else if ( aOptions[i].selected && bSwapEnabled )
			swapOptions( aOptions, i, i+1 ) ;
	}

	refreshOptionList() ;
}

// refresh list in hidden field
function refreshOptionList()
{
	frm = document.forms["cat_order_form"] ;

	lOptions = "" ;
	aOptions = frm.elements["cat_position"].options ;
	for ( i=0; i<aOptions.length; i++ )
		lOptions += ( i==0 ? '' : ',' ) +aOptions[i].value ;

	frm.elements["site_ordering"].value = lOptions ;
}

function swapOptions( aOptions, index1, index2 )
{
	txt = aOptions[index1].text ;
	val = aOptions[index1].value ;
	sel = aOptions[index1].selected ;

	aOptions[index1].text = aOptions[index2].text ;
	aOptions[index1].value = aOptions[index2].value ;
	aOptions[index1].selected = aOptions[index2].selected ;

	aOptions[index2].text = txt ;
	aOptions[index2].value = val ;
	aOptions[index2].selected = sel ;
}

function clear_opts( select_id ) {
    var select_obj = document.getElementById( select_id );
    if ( select_obj ) {
        for ( i=0; i<select_obj.length; i++ ) {
            select_obj[i].selected = false;
        }
    }
}

function toggle_div(toggleId, e)
{
    if (!e) {
        e = window.event;
    }

    if (!document.getElementById) {
        return false;
    }

    var help_div = document.getElementById(toggleId);

    if (!help_div) {
        return false;
    }

    if (help_div.style.display == 'none') {
        help_div.style.display = 'block';
    } else {
        help_div.style.display = 'none';
    }


    if (e) {
        // Stop the event from propagating, which
        // would cause the regular HREF link to
        // be followed, ruining our hard work.
        e.cancelBubble = true;
        if (e.stopPropagation) {
            e.stopPropagation();
        }
    }

    return false;
}

function getElementsByClassName(classname, node)  {
    if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++) {
        if(re.test(els[i].className))a.push(els[i]);
    }
    return a;
}

var selectedOptions = [];
function countSelected(select,maxNumber){

    for(var i=0; i<select.options.length; i++){

        if(select.options[i].selected && !new RegExp(i,'g').test(selectedOptions.toString())){
            selectedOptions.push(i);
        }

        if(!select.options[i].selected && new RegExp(i,'g').test(selectedOptions.toString())){
            selectedOptions = selectedOptions.sort(function(a,b){return a-b});
            for(var j=0; j<selectedOptions.length; j++){
                if(selectedOptions[j] == i){
                    selectedOptions.splice(j,1);
                }
            }
        }

        if(selectedOptions.length > maxNumber){
            alert('You may only choose '+maxNumber+' options!!');
            select.options[i].selected = false;
            selectedOptions.pop();
            document.body.focus();
        }
    }
}

