// System Tools
var System = {
    message: function(msg){
        alert(msg);
        //new Insertion.Top('outer','<div id="msgContainer"><div id="msg">'+msg+'<div id="msgClose" onclick="javascript:System.closeMessage()">close</div></div></div>');
    },
    closeMessage:function(){
        Element.remove('msgContainer');
    },
    confirm: function(msg){
        return confirm(msg);
    },
    debug: function(msg){
        if( Element.getDimensions('debug').height > 700 ) {
            System.clearDebug();
        }
        // Comment out next line to disable debugging msg
        // $('debug').innerHTML =   $('debug').innerHTML + msg + "<br />";
    },
    clearDebug: function(){
        // $('debug').innerHTML = "";
    }
}
/* Mimic A exclusive menu group */
var Menu =  Class.create();
Menu.prototype =  {

    nodes: [],
    opts: {},
    selected:null,
    msg: "yo",
    clickHandlers: {},
    toString: function () { return "Menu Object" } ,
    eventHandler: function(ev) {

        var self = Event.element(ev);
        System.debug("handler called:"+self);
        var _this = this;
        this.nodes.each(function (node){
            if( Element.hasClassName(node,_this.opts.selectClass ) ) {
                System.debug("Removing selectclass from:"+node.id);
                Element.removeClassName(node,_this.opts.selectClass )
            }
        });

        Element.addClassName(self,this.opts.selectClass );

        this.selected = self;

        _this = this;
        // Attempt to call a custom click handler if not then default
        return Try.these(
            function(){ _this.clickHandlers[self.id]() },
            function(){ _this.opts.clickHandler(ev) }
        );
    } ,
    addClickListener: function(id,fn) {
        var _id = typeof(id) == "string" ? id : $(id).id ;
        this.clickHandlers[id] = fn;
    },
    // Handle hover action
    hoverHandler: function(ev) {

        var self = Event.element(ev);
        if ( Element.hasClassName(self,this.opts.hoverClass ) ) {
                    Element.removeClassName(self,this.opts.hoverClass)
        } else  {
                    Element.addClassName(self,this.opts.hoverClass)
        }
    },
    initialize: function(conf) {
        // Setup up event objects
        this.events = {
              mouseOver:  this.hoverHandler.bindAsEventListener(this),
              mouseOut:  this.hoverHandler.bindAsEventListener(this),
              mouseClick:  this.eventHandler.bindAsEventListener(this)
        },
        this.opts = {
            parent:conf.parent,
            child:conf.child,
            hoverClass:conf.hoverClass,
            clickHandler:conf.clickHandler,
            selectClass:conf.selectClass
        }

        this.setup();
    },
    setup: function(){

        // Remove Event Listeners if present
        if(this.nodes){
            var _this = this;
            this.nodes.each( function(node){
                Event.stopObserving(node,'mouseover',_this.events.mouseOver,true);
                Event.stopObserving(node, 'mouseout',_this.events.mouseOut,true);
                Event.stopObserving(node,'click', _this.events.mouseClick,true);
            });
        }
        this.nodes = $A( $(this.opts.parent).getElementsByTagName(this.opts.child) );

        // Preserve scope for handler assignment
        _this = this;
        //System.clearDebug();
        this.nodes.each( function(node)
        {
            //System.debug("init:"+node.innerHTML);
            if( Element.hasClassName(node,_this.opts.selectClass ) ) {
                Element.removeClassName(node,_this.opts.selectClass )
            }
            if ( Element.hasClassName(node,_this.opts.hoverClass ) ) {
                Element.removeClassName(node,_this.opts.hoverClass)
            }

            Event.observe(node, 'mouseover',  _this.events.mouseOver, true);
            Event.observe(node, 'mouseout',  _this.events.mouseOut,true);
            Event.observe(node, 'click',  _this.events.mouseClick,true);

        });
        //Effect.Appear(_this.opts.parent,{duration:.2});
    },
    forceSelect: function(selectMe){
        var me = $(selectMe);
        var _this = this; // Temp scope fix

        this.nodes.each(function(node){
            if(node == me ) {
                Element.addClassName(node,_this.opts.selectClass );
                _this.selected = node;
            } else {
                Element.removeClassName(node,_this.opts.hoverClass);
                Element.removeClassName(node,_this.opts.selectClass);
            }
        });
    },
    forceSelectByIndex: function(id){
        var match = false;
        var _this = this;
        this.nodes.each(function(node){
            if( idSplit(node) == id ) {
                _this.forceSelect(node);
                System.debug("Selecting:"+node.id);
                match = true;
            }
        });
        //if( !match ) { alert("no match for "+id+" in "+_this.opts.parent); };
    },
    deselectAll: function()
    {
        _this = this;
        this.nodes.each(function(node){
            Element.removeClassName(node,_this.opts.hoverClass);
            Element.removeClassName(node,_this.opts.selectClass);
            this.selected = null;
        });
    }
}

/************************
*       Helpers      *
************************/
// Pass in an array of [selectelement,index] pairs
var Select = {

    setByValue:  function(nodes)
    {

        for( var item in nodes ) {
                var element = $(item);
                //System.debug("Searching:"+element.id+" for :"+nodes[item] );
                var opts = element.options;
                for( var a = 0 ; a < opts.length ; a++ )
                {
                    if ( opts[a].value == nodes[item] ){
                        //System.debug("!found: "+nodes[item]+" at index: " + a);
                        element.selectedIndex = a;
                        break;
                    }
                }
        }
    }
}
/* Return the index suffix from a css id : selector(_index)  */
var idSplit = function(el){
    var id =  el.id.match(/_([^_]+)$/)[1];
    System.debug("found id:"+id+ " in:"+el.id);
    return id;
}
/* JS port of uppercase words  */
String.prototype.ucwords = function(){
    var ucstring = "";
    var temp = $A(this.split(" "));
    temp.each(function(s){
        ucstring += ( s.length > 1 ) ? s.substr(0,1).toUpperCase() + s.substr(1,s.length-1) : s.toUpperCase() ;
    });
    return ucstring;
}
/* Strip Slashes From incoming string */
String.prototype.stripslashes = function(){
    var str = this;
    str=str.replace(/\\'/g,'\'');
    str=str.replace(/\\"/g,'"');
    str=str.replace(/\\\\/g,'\\');
    str=str.replace(/\\0/g,'\0');
    return str;
}

/*
*   Pre load image rollovers and setup rollover events
*   Rollovers images must have the _over suffix
*   Note: Requires prototype obviously
*/
function rollOver(obj)
{
    var nm = obj.src.match(/^(.*?)(_over)?\.(\w+)$/i);
    obj.src = ( nm[2] == "_over" ) ? nm[1]+"."+nm[3] : nm[1]+"_over"+"."+nm[3];
}
var rolloverimages = Array();
function setupRollOver(parent,child)
{
    var nodes = $A( $(parent).getElementsByTagName(child) );
    nodes.each(function(node){
        if( ! node.src.match(/_over/i) ) {
            var n = node.src.match(/^(.*?)\.(\w+)$/i);
            var i = new Image();
            i.src=n[1]+"_over."+n[2];
            rolloverimages.push(i);
            node.onmouseover = node.onmouseout = function(){rollOver(this); }
        }
    });
}
/* Sitewide Help Box */
var Help = {
    cache:{},
    init:function(){
        // Select a random item initialy
        var h = $('help');
        var n =Math.floor(Math.random()*$('help').options.length);
        h.selectedIndex = n;
        Help.get();
    },
    get:function(){
        var id = $F('help');
        if(Help.cache[id]) {
            Element.update('helptext',Help.cache[id]);
        } else {
            Element.update('helptext','<img src="images/loader_trans.gif" />');
            
            
            url = window.location.href;
            regex = /https:/;
            matchpos = url.search(regex);

            if(matchpos != -1)
            {
                var ajax = new Ajax.Updater('helptext','https://www.sgleisure.org/ajax',
                             {
                             method:'post',
                             postBody:'action=getHelp&id='+id,
                             onComplete:function(t){Help.cache[id]=t.responseText}
                             });            
            }  
            else
            {
                var ajax = new Ajax.Updater('helptext','ajax',
                             {
                             method:'post',
                             postBody:'action=getHelp&id='+id,
                             onComplete:function(t){Help.cache[id]=t.responseText}
                             });
            }
            
        }
    }
}


var PopUp = {
    swimming:function(){
        var swim = window.open("/flash/swimming.html","swim","width=698,height=550");
    },
    gymTour:function(){
        var gym = window.open("/flash/gymtour.html","gym","width=680,height=390");
    },
    tools:function(){
        var tools = window.open("/flash/tools.html","tools","width=698,height=464");
    },
    slideshow:function() {
        var tools = window.open("/flash/slideshow.html","slideshow","width=680,height=390");
    },
    video:function() {
        var video = window.open("/flash/video.php?v=/media/cock_road_ridge_may_vp6_768.flv", "slideshow", "width=478,height=340");

    }
}

function homeSearch(){
    if( $F('homeSearchSelect') != "0" ){
    location.href=$F('homeSearchSelect');
    }
}
function ActivityRedirect(){
    if( $F('activity_type') != "0" )
    {
        location.href='/sgl/activities/timetables?activity='+$F('activity_type');
    }
}


// Field Validator Functions --------------------------------------------------------
var validators = {
        text:function(n){       return !/^\s*$/g.test(n.value) },
        telephone:function(n){  return /^\s*[\d]{2,8}\s*(([\d]{2,})\s*)+\s*$/.test(n.value) },
        email:function(n){      return /^[A-Za-z0-9._%-]{3,}@[A-Za-z0-9.-]{3,}\.[A-Za-z]{2,6}$/.test(n.value)},
        number:function(n) {    return /^\s*\d+\s*$/.test(n.value) },
        noblank:function(n) {   return !/^\s*$/.test(n.value) },
        checked:function(n) {   return n.checked==true; },
        date:function(n) { return /^\s*\d\d?[^\d]+\d\d?[^\d]+\d\d(\d\d)?\s*$/.test(n.value) },
        select:function(n) { return n.value !=0 } 
}
// Form validator
var Validate = function(){}
Validate.prototype = {

    fields:{},
    alerts:[],
    valid:true,
    attempt:function(formName)
    {
        formName = formName || document.forms[0];
        var me = this;
        //alert(typeof(formName));
        var f = typeof(formName) == 'string' ? document.forms[formName] : formName;
        var elements = f.elements;
        //alert(elements.length)
        for( var a = 0 ; a < elements.length; a++ ) {

            if( elements[a].type != 'submit'  ) {
                //alert("current:"+elements[a].type + " " + elements[a].id);
                var el = elements[a];

                try {
                    console.log('Trying ' + el.name);
                    if( this.fields[el.name] ) {

                            // Validate a radio button group
                            if( el.type == 'radio' )
                            {
                                var m = el.id.match(/^(\w+)_(\d)+$/);
                                var item_name = m[1];
                                var item_suffix = m[2];
                                var items = [];
                                var v = false;
                                while(e = f.elements[item_name+"_"+(item_suffix++)] ) {
                                    items.push(e);
                                    //alert('pushing');
                                }

                                for( var i = 0 ; i < items.length ; i++ ) {
                                    if( items[i].checked ){
                                        //alert("checked"+items[i]);
                                        v = true;
                                        break;
                                    }
                                }

                                if( !v )
                                    for( var i = 0 ; i < items.length ; i++ )
                                        this.hint(items[i].previousSibling,true);
                                else
                                    for( var i = 0 ; i < items.length ; i++ )
                                        this.hint(items[i].previousSibling,false);

                                a += items.length-1;
                            }
                            else
                             {
                                if( !validators[this.fields[el.name][0]](el) ) {
                                    //alert(el.id+ " " + validators[this.fields[el.id][0]](el));
                                    this.valid = false;
                                    this.hint(el,true);
                                    if ( this.fields[el.id][1] != '') this.alerts.push(this.fields[el.id][1]);
                                } else {
                                    this.hint(el,false);
                                }
                            }


                    }
                } catch(e) {
                    console.log('error:'+e.id + " " + e.message);
                    continue;
                }

            }
        }

        return this.valid;
    },
    alertString:function(){
        return (this.alerts.length>0?'\n '+this.alerts.join('\n '):'')
    },
    hint:function(el,state)
    {
        // Comment out to show which element and which type hoo ha!
        // alert( el.id + " " + el.type )
        // console.log("Hinting : "+el.id + " type: " + el.type ); // Firebug
        if( el.type == "select-one")
            {
            if( state == true ) {
                if( !/hint/.test(el.className) ) {
                    el.className += ' hint-select';
                }
            }
            else {
                el.className = el.className.replace(/hint-select/,'');
            }
        } 
        else
            {
            if( state == true ) {
                if( !/hint/.test(el.className) ) {
                    el.className += ' hint';
                }
            }
            else {
                el.className = el.className.replace(/hint/,'');
            }
        }
    }
}


function onSubmitLongwellSwimming(){

    var f = new Validate();

    f.fields = {
        contact_name:['text',''],
        telephone:['telephone',''],
        email:['email',''],
        postcode:['text',''],
        name:['text',''],
        dob:['date','']
    }

    if( !f.attempt('main-form') ) {
        alert('Please correct the relevant fields' + (f.alerts.length>0?'\n '+f.alerts.join('\n '):'') );
    }
    else {

    var data = Form.serialize('main-form');
    Element.update('form-container','<p><img src="/images/loader_trans.gif" /> Submitting Data Please wait ..</p>');

    var ajax = new Ajax.Updater('form-container','/ajax',
                                {
                                    method:'post',
                                    parameters:data
                                }
                                );
    }

    return false;
}

function onSubmitLongwellHealth(){

    var f = new Validate();

    f.fields = {
        contact_name:['text',''],
        telephone:['telephone',''],
        email:['email',''],
        postcode:['text',''],
        name:['text',''],
        dob:['date',''],
        sex:['checked','']

    }

    if( !f.attempt('main-form') )
        alert('Please correct the relevant fields' + (f.alerts.length>0?'\n '+f.alerts.join('\n '):'') );
    else {

        var data = Form.serialize('main-form');
        Element.update('form-container','<p><img src="/images/loader_trans.gif" /> Submitting Data Please wait ..</p>');
        var ajax = new Ajax.Updater('form-container','/ajax',
                                    {
                                        method:'post',
                                        parameters:data,
                                        evalScripts:true
                                    }
                                    );
    }


    return false;

}


function onSubmitGymComp(){

    var f = new Validate();

    f.fields = {
        name:['text',''],
        telephone:['telephone',''],
        email:['email',''],
        postcode:['text',''],
        name:['text',''],
        dob:['date','DOB in dd/mm/yy format please.'],
        sex:['checked',''],
        dob:['date',''],
        which_gym:['select',''],
        what_time:['select',''],
        how_hear:['checked','']
    }

    if( !f.attempt('main-form') )
        alert('Please correct the relevant fields' + (f.alerts.length>0?'\n '+f.alerts.join('\n '):'') );
    else {

        var data = Form.serialize('main-form');
        Element.update('form-container','<p><img src="/images/loader_trans.gif" /> Submitting Data Please wait ..</p>');
        var ajax = new Ajax.Updater('form-container','/ajax',
                                    {
                                        method:'post',
                                        parameters:data,
                                        evalScripts:true
                                    }
                                    );
    }


    return false;

}

function setHint(element, val) {
    LOG('Source element:' + element.id);    
    var element = $($(element).parentNode);
    LOG('Set Hint: ' + element + ' ' + val);
    if(val)  
        element.removeClassName('hint');
    else {
        element.addClassName('hint');
    }
}

function LOG(msg){
    try{ console.log(msg) } catch(e) { }
}

function onSubmitYateReg(){

    var is_valid = true;

    var fields = {
        title:['select', ''],    
        firstname:['text',''],
        lastname:['text',''],
        dob_year:['select', ''],
        dob_month:['select', ''],
        dob_day:['select', ''],
        sex:['checked', ''],
        address:['text', ''], 
        postcode:['text', ''], 
        email:['email', ''], 
        tel_home:['text', ''],
        tel_work:['text', ''],
        which_facility:['select', ''],
        which_site:['select', ''],
        please_call:['checked', ''],
        how_hear:['select',''],
        time_of_day:['text', ''],
        times_per_week:['select' ,''],
        enquiring_for:['select',  ''],
        member_elsewhere:['checked',''],
        what_achieve:['select','']
    }

   
    for(el in fields)
    {
        var field = $(el);
        var type = fields[el][0];
        var validator = validators[fields[el][0]];
        switch(type)
        {
            case "checked":
               var c = 1;
               var collected = [];
               var ok = false;
               var radio_btn = null;
               while( radio_btn = $(el+"_"+(c++)) ) {
                  if(radio_btn == null) break;
                  collected.push(radio_btn);
                  ok = ok || validator(radio_btn)
               }
               setHint(collected[0], ok)
               tested_field = collected[0]; 
               is_valid = is_valid && ok
            break;
            default:
               var ok = validators[fields[el][0]](field);
               LOG('el validation=' + ok);
               setHint(field, ok);
               is_valid = is_valid && ok;
            break;
        }
        LOG('Field: ' + el + ' as:' + type + ' result:' + ok) ;
    }    
    if(!is_valid)
    {
       alert('Please correct the highlighted fields'); 
    }
    else    
    {
        
        var data = Form.serialize('main-form');
     
        Element.update('form-container','<p><img src="/images/loader_trans.gif" /> Submitting Data Please wait ..</p>');
        
        var ajax = new Ajax.Updater('form-container','https://www.sgleisure.org/ajax', {
            method:'post',
            parameters:data,
            onSuccess: function(response) {
              //alert('success');
            }
        });
    }
    return false;
}
