window.addEvent('domready', function() {
    var el = $('home');
    var high = true;
    to_show = location.href.split('#')[1];
    if (!to_show)
        to_show = 'home';
    //document.getElementById('field_10').disabled = false;
    //alert(to_show);
    var list = $$('#wrap div, #sub_navigation'); // list of collapsible elements
    var headings = $$('#navigation a, #sub_navigation a'); // list of elements to be clicked on
    headings.splice(3,1);

    var mpl = $('music_popup');
    var old_music_href = mpl.getAttributeNode("href").nodeValue;
    mpl.removeAttributeNode(mpl.getAttributeNode("href"));

    $('music_popup').onclick = music_popup;

    window.onunload = music_popup_exit;


    function music_popup_exit(evt) {
        var show_player = confirm("Would you like to continue listening to the music?");
        if ( show_player===true ) {
            if (!popup_window) {
                //alert('no popup exists');
                popup_window = music_player_popup("popup.html");
                return preventDefaultAction(evt);
            }
            else {
                //alert('popup exists');
                popup_window.focus();
            }
        }
        else {
            if (popup_window && popup_window.close)
                popup_window.close();
        }
    }

    function music_popup(evt) {
        popup(old_music_href, 'fullscreen', 'fullscreen');
        return preventDefaultAction(evt);
    }

    function preventDefaultAction(evt) {
       if (evt) {
          if (typeof evt.preventDefault!= 'undefined') {
             evt.preventDefault(); // W3C
          } else {
             evt.returnValue = false; // IE
          }
       }
       return false;
    }

    abort_request();

    var test = new Image();
    var tmp = new Date();
    var suffix = tmp.getTime();
    test.src = 'images/do_not_delete_img_test.gif?'+suffix;
    test.onload = imageReplacement;

    function imageReplacement()
    {
      replaceThem(document.getElementsByTagName('h1'));
      replaceThem(document.getElementsByTagName('h2'));
      replaceThem(document.getElementsByTagName('h3'));
      replaceThem(document.getElementsByTagName('h4'));
    }

    function replaceThem(x)
    {
      var replace = document.createElement('img');
      for (var i=0;i<x.length;i++)
      {
        if (x[i].id)
        {
          var y = replace.cloneNode(true);
          y.src = 'images/' + x[i].id + '.gif';
          y.alt = x[i].firstChild.nodeValue;
          try {
                x[i].replaceChild(y,x[i].firstChild);
            }
            catch(e){}
        }
      }
    }

/*     var who = $('sub_navigation');
    var collapsible = new Fx.Slide(who, {
            duration: 500,
            transition: Fx.Transitions.Expo.easeIn
    });
    collapsibles['sub_navigation'] = collapsible;
    //var myFx = new Fx.Tween(item);
    //myFx.start('opacity', 1, 0);
    collapsible.hide();
    hide('sub_navigation');
*/

/*
    $('open_store').onclick = function() {
        var url = this.href;
        popup(url, 800, 600);
        return false;
    }
*/

    list.each(
        function(item, i) {
            //alert(item.id);

                var collapsible = new Fx.Slide(item, {
                        duration: 500,
                        transition: Fx.Transitions.Expo.easeIn
                });
                collapsibles[item.id] = collapsible;
                if (item.id!=to_show) {
                    if (item.id!="sub_navigation") {
                        var myFx = new Fx.Tween(item);
                        myFx.start('opacity', 1, 0);
                    }
                    //go_headings(item.id, false);
                    collapsible.hide();
                    hide(item.id);
                }

        }
    );

    headings.each( function(heading, i) {
            //for each element create a slide effect
            heading.onclick = et_toggle;
    });


    /* contact form */

    var form = $('contact_form');
    var check_radios = true;
    var ajax_url = {};

    if (document.styleSheets) {
        form.onsubmit = function() {
            check_radios = true;
            ajax_url = {};
            message('message_div', '', '');
            var error = error_checks();
            if (error===false) {
                var data = url_make('ajax/form.php', ajax_url);
                //alert('ajax(\'form.php\', \'form_submit_return\', \'' + url + '\')');
                //set_display('field_10', 0);
                ajax(data, 'form_submit_return');
                //document.getElementById('field_10').disabled = true;
            }
            else {
                //alert('message');
                message('message_div', error, 'warning');
            }

            return false;
        }
    }


    function error_checks() {
        var i, fieldname, field, content;
        var fields = form.getElementsByTagName('input');
        var err_msg = false;
        var error_messages = [];
        error_messages['null'] = 'Please complete all fields';
        error_messages['email'] = 'That is not a valid email address, please enter another.';
        error_messages['spam'] = 'Your answer is incorrect, please choose again.';
        error_messages['long'] = 'The text in this field is too long, please revise.';
        var error_type;

        for (i=0; i<fields.length; i++) {
            field = fields[i];
            if (i==fields.length-1)
                field = form.getElementsByTagName('textarea')[0];
            error(field, 0);
            if ((field.type=='radio') && (!check_radios))
                continue;
            content = get_value_of_field(field);
            if ( !content ) {
                error(field);
                err_msg = error_messages['null'];
            }
            else {
                if ((field.id=='field_5') && (!isValidEmail(content)) && (!err_msg) ) {
                    error(field);
                    return error_messages['email'];
                }
                if ((field.name=='field_9') && (content!=2) && (!err_msg) ) {
                    error(field);
                    return error_messages['spam'];
                }
                var maxlength = (field.type=='textarea') ? 5000 : (255+64);
                if (maxlength < content.length) {
                    error(field);
                    return error_messages['long'];
                }

                if (field.name=='field_9')
                    ajax_url['field_9'] = content;
                else
                    ajax_url[field.id] = content.stripX();
            }
        }
        return err_msg;
    }

    function get_value_of_field(field) {
        var val;
        switch (field.type) {
            case 'text':
                val = field.value;
                break;
            case 'textarea':
                val = field.value;
                break;
            case 'radio':
                if (check_radios)
                    check_radios = false;
                var radios = field.form[field.name];
                for (var i=0;i<radios.length;i++) {
                    if (radios[i].checked)
                        val = (i+1);
                }
                break;
            case 'checkbox':
                if (field.checked)
                    val = field.value;
                break;
        }
        return val;
    }


    function isValidEmail(str) {
        var atSym = str.lastIndexOf("@");
        if (atSym < 1) { return false; } // no local-part
        if (atSym == str.length - 1) { return false; } // no domain
        if (atSym > 64) { return false; } // there may only be 64 octets in the local-part
        if (str.length - atSym > 255) { return false; } // there may only be 255 octets in the domain
        var lastDot = str.lastIndexOf(".");
        if (lastDot > atSym + 1 && lastDot < str.length - 1) { return true; }
        if (str.charAt(atSym + 1) == '[' &&  str.charAt(str.length - 1) == ']') { return true; }
        return false;
    }

    function url_make(base, obj) {
        var url = (!base) ? '' : base+"?";
        var j = 0;
        for (i in obj) {
            if (j!=0) {
                url += "&";
            }
            obj[i] = escape(obj[i]);
            url += i + "=" + obj[i];

            j++;
        }
        return url;
    }




});

    function error(field,on) {
        var to = (on==0) ? '' : 'error';
        if (field.parentNode.getElementsByTagName('label')[0])
            field.parentNode.getElementsByTagName('label')[0].className = to;

    }


    function reset_form() {
        var i;
        var form = $('contact_form');
        var fields = form.getElementsByTagName('input');
        for (i=0; i<fields.length; i++) {
            field = fields[i];
            if (i==fields.length-1)
                field = form.getElementsByTagName('textarea')[0];
            error(field, 0);
            field.value = '';
        }
        message('message_div', '', '');
    }


    function form_submit_return(req) {
        clear_wait();
        var response = parse_JSON(req);
        var result = response.info.result;

        set_class('message_div', '');
        //document.getElementById('field_10').disabled = false;

        switch (result) {
            case 0: // error
                var field = response.info.field;
                if (!field) {
                    message('message_div', response.info.message.stripX(1), 'warning');
                    alert('field is not valid');
                    return false;
                }
                //alert(field);
                if (field != 'field_9') {
                    field = document.getElementById(field);
                    error(field);
                }
                message('message_div', response.info.message.stripX(1), 'warning');
                break;

            case 1:
                message('message_div', response.info.message.stripX(1), 'warning');
                var form = $('contact_form');
                var fields = form.getElementsByTagName('input');
                for (i=0; i<fields.length; i++) {
                    var field = fields[i];
                    if (i==fields.length-1)
                        field = form.getElementsByTagName('textarea')[0];
                    if ( (field.type=='text') || (field.type=='textarea') ) {
                        field.value = '';
                    }
                }
                break;

            default:
                alert(response.info.message.stripX(1));
                break;
        }
    }

    /*
        set class to class_to of element defined by id
    */
    function set_class(id, class_to) {
        var the_div = document.getElementById(id);
        if ( the_div ) {
            //alert(the_div.id + ' : ' + class_to);
            the_div.className = class_to;
        }
    }

    /*
        show or hide elements identified by id
    */
    function set_display(id, on, inline) {
        var the_div = document.getElementById(id);
        if (the_div) {
            if (on==1) {
                the_div.style.display = (inline==1) ? "inline" : "block";
            }
            else
                the_div.style.display = "none";
        }
    }


    /* encode or decode common html entities
       called like: textstring.stripX(1)
       where textstring is a string          */
    String.prototype.stripX = function(boo){
        var str= this;
        if(boo){
            str= str.replace(/\&amp;/g,'&');
            str= str.replace(/\&lt;/g,'<');
            str= str.replace(/\&quot;/g,'"');
            str= str.replace(/\&gt;/g,'>');
        }
        else{
            str= str.replace(/\&/g,'&amp;');
            str= str.replace(/</g,'&lt;');
            str= str.replace(/\"/g,'&quot;');
            str= str.replace(/>/g,'&gt;');
        }
        return str;
    };

    /*
        display txt in div identified by id
        also set class of div to class_to
        else clears it by setting it to ''
    */
    function message(id, txt, class_to) {
        div = document.getElementById(id);
        if (div) {
            if (!class_to)
                class_to = "";
            set_class(id, class_to);
            div.innerHTML = txt;
            //alert(div.id + ' : ' + div.innerHTML + ' : ' + ' :' + class_to);
            set_display(id, 1);
        }
        else
            alert(txt);
    }


    function popup(url, width, height) {
        if ( (width=='fullscreen') && (screen.width) )
            width = screen.width;
        if ( (height=='fullscreen') && (screen.height) )
            height = screen.height;
        var options = "resizable=yes,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,left=0,top=0";
        /* NB, as iemand verander - moenie spasies sit in naam, IE errors */
        myWin = window.open(url, "PhonoMondo", options);
        if (myWin) {
            myWin.resizeTo(width, height);
            //myWin.moveTo(100,100);
            return false;
        }
        return true;
    }


    var popup_window = '';

    function music_player_popup(url) {
        if (!popup_window.closed && popup_window.location) { /* no popup so far */
            popup_window.location.href = url;
        }
        else {
            var features = 'location=0,status=0,menubar=0,resizable=no,scrollbars=no,top=50,left=50,screenX=100,screenY=100,width=290,height=260';
            var theWindow = window.open(url, '_blank', features);
            if ( theWindow && (!theWindow.opener) )
                theWindow.opener = self;
            popup_window = theWindow;
        }
        if (popup_window && popup_window.focus) {
            popup_window.focus();
        }
        return false;
    }




