var Site = {
    start: function(){
        var editableForms = $$('.textholder');
        editableForms.each(function(ef, i){
            new eip( ef, '/update.php', {update: '1', updatecontent: '1'});
        });
        Site.createForms();
        Site.pageConf();
        Site.externalLinks();
        Site.bookings();
        Site.availability();
        if ($('admintoggle')) { Site.adminToggle(); }
    },
    
    bookings : function() {
        var days = $$('td.day');
        days.each(function(d, i) {
            d.addEvent('click', function(e) {
                var place = d.getProperty('place');
                d.addClass('working');
                new Ajax("/update.php?book_date=1&place="+place+"&date="+d.getProperty('rel'), {
                    method: 'get',
                    onComplete:function(resp){
                        if (resp == 0) {
                            d.removeClass('checked');
                            d.removeClass('working');
                        }
                        else {
                            d.addClass('checked');
                            d.removeClass('working');
                        }
                    }
                }).request();
            });
        });
    },
    
    availability : function() {
        if ($('submitform')) {
            var f = new Element('form', {
                    'id' : 'theform',
                    'method' : 'post',
                    'action' : '/availability.php'
            }).injectInside($('submitform'));
            var submit = new Element('input', {
                'type': 'image',
                'src': '/images/book_now.png',
                'style': 'margin-left:120px;'
            }).injectInside(f);
        }
        var days = $$('td.available');
        days.each(function(d,i) {
            d.addEvent('click', function(e) {
                var place = d.getProperty('place');
                var formentry = new Element('input', { 'type':'hidden','name': 'place','value':place}).injectInside(f);
                if (!d.hasClass('booked')) {
                    var formentry = new Element('input', { 'type':'hidden','name': 'dates[]','value':d.getProperty('rel'), 'class': d.getProperty('rel')}).injectInside(f);
                    d.addClass('booked');
                }
                else {
                    d.removeClass('booked');
                    f.getElement('input.'+d.getProperty('rel')).remove();
                }
            });
        });
    },
    
    
    changePic : function(pic) {
        var target = $('gallery_target');
        $(target).setStyle('background', 'url:(images/'+pic+')');
    },
    
    externalLinks : function() {
        $$('a.external').each(function(link) {
            link.target = '_blank';
        });
    },
    
    pop: function(url) {
        //var h=window.availHeight/2;
        //var w=(window.availWidth/1.25).round();
        //var w=window.availWidth/2;
        var w = 920;
        var h = 780;
        var l=0;
        window.open("/getimg.php?img="+url,'_blank', 'height='+h+',left=75,location=0,resizable=1,toolbar=0,top=100,width='+w+',scrollbars=1',false);
    },
    
    adminToggle : function() {
        var next = $('admintoggle').getNext();
        var mySlide = new Fx.Slide(next);
        //Create a slide in/out
        $('admintoggle').addEvent('click', function(e){//add the click function (i.e on an anchor)
        e = new Event(e);//create a new event here
        mySlide.toggle();//do this to the selected element
        if (mySlide.open) { $('admintoggle').setHTML('&dArr;Admin Control Panel&dArr;'); }
        else { $('admintoggle').setHTML('&uArr;Admin Control Panel&uArr;'); }
        e.stop();//stop the event
        });
    },


    createForms : function() {
        var ajaxForms = $$('.ajaxform');
	ajaxForms.each(function(forms, i){
            //if (!window.ie6) {
                new FormValidator(forms, {onFormValidate: function(isPassed, form) {
                    if (isPassed == true) {
                        var sz = form.getProperty('action');
                        //if (form.hasClass('szu')) { sz = '/update.php' }
                        //else if (form.hasClass('szl')) { sz = '/login.php' }
                        //var cFH = form.getParent().empty().addClass('ajax-loading');
                        var cFH = form.getParent().addClass('ajax-loading');
                        var myAjax = new Ajax(sz,{
                            postBody: form,
                            update: cFH,
                            onComplete: function(resp) {
                                cFH.removeClass('ajax-loading');
                                //new Event(isPassed).stop();
                            }
                        }).request();
                    }
                }});
            //}
        });
    },
    
    pageConf : function() {
        if ($chk($('pageConf'))) {
        $('pageConf').addEvent('click', function(e) {
            // get id
            var tid = $('pageConf').getProperty('class');
            var id = tid.substring(2);
            
            var myDiv = new Element('div', {
                'name': 'content',
                'id' : 'pageConfig',
                'style': 'margin-left:250px'
            }).injectTop($('container'));
            
            var form = new Element('form', {
                'id': 'form_config',
                'method' : 'post',
                'action': '/update.php'
            });
            
            el = myDiv;
            target = 'headline';

            // Store new form in the element
            el.form = form;
            
            // Need this to pass to the buttons
            var obj = this;
            
            new Element('label', {
                'for' : 'pagetitleage'
            }).appendText('Page Title:').injectInside(form);
            
            // Create a textarea or input for user
            var input1 = new Element('textarea', {
                'name': 'title',
                'style': 'height: 25px;width: 750px;',
                'id' : 'pagetitleage'
            }).appendText('Getting content from server...').injectInside(form);
            
            new Element('div', {'class': 'cls'}).setHTML(' ').injectInside(form);
            
            new Element('label', {
                'for' : 'headline'
            }).appendText('Page Description:').injectInside(form);
            
            // Create a textarea or input for user
            var input = new Element('textarea', {
                'name': 'content',
                'style': 'height: 25px;width: 750px;',
                'id' : 'headline'
            }).appendText('Getting content from server...').injectInside(form);
            
            new Element('div', {'class': 'cls'}).setHTML(' ').injectInside(form);
            
            new Element('label', {
                'for' : 'keywords'
            }).appendText('Page Keywords:').injectInside(form);
            
            // Create a textarea or input for user
            var input2 = new Element('textarea', {
                'name': 'keywords',
                'style': 'height: 25px;width: 750px;',
                'id' : 'keywords'
            }).appendText('Getting content from server...').injectInside(form);
            
            new Element('div', {'class': 'cls'}).setHTML(' ').injectInside(form);
            
            new Element('label', {
                'for' : 'weight'
            }).appendText('Page Weight:').injectInside(form);
            
            // Create a textarea or input for user
            var input3 = new Element('textarea', {
                'name': 'weight',
                'style': 'height: 25px;width: 750px;',
                'id' : 'weight'
            }).appendText('Getting content from server...').injectInside(form);
            
            new Element('div', {'class': 'cls'}).setHTML(' ').injectInside(form);
            
            new Element('label', {
                'for' : 'submit'
            }).appendText('').injectInside(form);
            
            // Add a submit button
            new Element('input', {
                'type': 'submit',
                'value': 'save',
                'class': 'submitbutton',
                'style': 'font-weight: bold;margin-left:710px;',
                'events': {
                    'click': function(evt){
                        (new Event(evt)).stop();
                        form.send({update: el});
                        //setTimeout(function(){$('settings').remove();},4000);
                    }
                }
            }).injectInside(form);
            
            
            new Element('input', {
                'type': 'hidden',
                'name': 'id',
                'value': id
            }).injectInside(form);
            new Element('input', { 'type': 'hidden', 'name': 'update', 'value': 1}).injectInside(form);
            new Element('input', { 'type': 'hidden', 'name': 'updatecontent', 'value': 1 }).injectInside(form);
            
            // inject our target
            new Element('input', {'type': 'hidden','name': 'target','value': target }).injectInside(form);

            // Add the form after the target element
            form.injectInside(el);
            
            // now populate our ajax request
            url = "?getcontent=1&id="+id+"&target="+target;
            var rq = new Ajax("/update.php"+url, {
                method: 'get',
                onComplete:function(resp){
                    var content = resp;
                    input.setText(resp);
                    $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', ''); });
                    el.setProperty('disabled', '');
                }
            }).request();
            
            // now populate our ajax request
            url = "?getcontent=1&id="+id+"&target=title";
            var rq = new Ajax("/update.php"+url, {
                method: 'get',
                onComplete:function(resp){
                    var content = resp;
                    input1.setText(resp);
                    $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', ''); });
                    el.setProperty('disabled', '');
                }
            }).request();
            
            url = "?getcontent=1&id="+id+"&target=keywords";
            var rq = new Ajax("/update.php"+url, {
                method: 'get',
                onComplete:function(resp){
                    var content = resp;
                    input2.setText(resp);
                    $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', ''); });
                    el.setProperty('disabled', '');
                }
            }).request();
            
            url = "?getcontent=1&id="+id+"&target=weight";
            var rq = new Ajax("/update.php"+url, {
                method: 'get',
                onComplete:function(resp){
                    var content = resp;
                    input3.setText(resp);
                    $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', ''); });
                    el.setProperty('disabled', '');
                }
            }).request();
        });
        }
        
    }
};

var eip = new Class({
    /**
     * Initialize
     * @param elements els An array of elements.
     * @param string action the path to the file to target with form.
     * @param object params (optional) Any extra parameters you would like to send with the AJAX call.
     * @param object options (optional) Override the default classes with this.
     */
    initialize: function(els, action, params, options) {
        // Handle array of elements or single element
        if ($type(els) == 'array') {
                els.each(function(el){
                        this.prepForm(el);
                }.bind(this));
        } else if ($type(els) == 'element') {
                this.prepForm(els);
        } else {
                return;
        }

        // Store the action (path to file) and params
        this.action = action;
        this.params = params;

        // Default options
        this.options = Object.extend({
                overCl: 'over',
                hiddenCl: 'hidden',
                editableCl: 'edittextarea',
                textareaCl: 'textarea'
        }, options || {} );
    },
    
    /**
     * Add events to element
     * @param element el Your target element.
     */
    prepForm: function(el) {
        var obj = this;
        el.addEvents({
                'mouseover': function(){this.addClass(obj.options.overCl);this.setProperty('title','Double click here to edit')},
                'mouseout': function(){this.removeClass(obj.options.overCl);},
                'dblclick': function(){obj.showForm(this);}
        });
    },


    /**
    * Build and/or show form
    * @param element el Your target element.
    */
    showForm: function(el) {
        var classes = el.getProperty('class').split(" ");
        for (i=classes.length-1;i>=0;i--) {
            if (classes[i].contains('type:')) {
                var target = classes[i].split(":")[1];
            }
            else if (classes[i].contains('id:')) {
                var id = classes[i].split(":")[1];
            }
        }
        var height = el.getStyle('height').toInt();
        //height = height + 12 + 'px';
        (height < 85) ? height = height + 'px' : height = height + 24 + 'px';
        
        
        // Hide target element
        el.addClass(this.options.hiddenCl);

        // If the form exists already, let's show that
        if (el.form) {
            el.form.removeClass(this.options.hiddenCl);
            //el.form[target].focus();
            return;
        }

        // Create new form
        var form = new Element('form', {
            'id': 'form_' + id,
            'action': this.action,
            'class': this.options.editableCl
        });

        // Store new form in the element
        el.form = form;
        
        // Need this to pass to the buttons
        var obj = this;

        var divholder = new Element('div', {
            'class': 'editboxholder'
        }).injectInside(form);

        //var ulholder = new Element('ul', {
        //    'class': 'editul'
        //}).injectInside(form);
        
        // Add a submit button
        new Element('input', {
            'type': 'submit',
            'value': 'save',
            'class': 'submitbutton',
            'style': 'font-weight: bold',
            'events': {
                'click': function(evt){
                    (new Event(evt)).stop();
                    el.empty();
                    el.appendText('saving...');
                    obj.hideForm(form, el);
                    form.send({update: el});
                }
            }
        }).injectInside(divholder);
        

        // Add a cancel button
        new Element('input', {
            'type': 'button',
            'value': 'cancel',
            'class': 'submitbutton',
            'style': 'margin-left:4px;',
            'events': {
                'click': function(form, el){
                    obj.hideForm(form, el);
                    //alert("form: "+form+" el: "+el);
                    //(new Event(form,el)).stop();
                }.pass([form, el])
            }
        }).injectInside(divholder);
        
        var big = 0;
        var oldstyles;
        new Element('input', {
            'type': 'button',
            'value': '<->',
            'class': 'submitbutton',
            'style': 'margin-left:4px;',
            //'style': 'margin:0;margin: 0 0 0 305px; padding: 0',
            'title': 'Expand/Contract width of EditBox',
            'events': {
                'click': function(form, el){
                    (new Event(form,el)).stop();
                    if (big == 0) {
                        // change to big
                        var neww = $('main').getStyle('width').toInt();
                        input.setStyles({
                        'position': 'absolute',
                        'display': 'block',
                        'left': '-2px',
                        'width': neww +"px",
                        'overflow': 'visible',
                        'z-index': '5000'
                        });
                        big = 1;
                        return 0;
                    }
                    else if (big == 1) {
                        //change to normal
                        input.setStyles(oldstyles);
                        big = 0;
                        return 0;
                    }
                    return 0; // will never get here
                }
            }
        }).injectInside(divholder);
        
        
        /*new Element('input', {
            'type':'button',
            'value':'Show Help',
            'class':'submitbutton',
            'title':'Display Quick Help',
            'id': 'helplink',
            'style': 'margin:0;margin-left:30px;padding-left:20px;',
            'events': {
                'click': function(link) {
                    (new Event(link)).stop();
                    if ($('helpbox') && $('helpbox').getStyle('display') != 'none') {
                        $('helplink').setProperty('value','Show Help');
                        $('helpbox').setStyle('display', 'none');
                    }
                    else if ( $('helpbox') && $('helpbox').getStyle('display') == 'none') {
                        $('helpbox').setStyle('display', 'block');
                        $('helplink').setProperty('value','Hide Help');
                    }
                    else {
                        $('helplink').setProperty('value','Hide Help');
                        new Element('div', {
                            'id' : 'helpbox',
                            'style': 'clear:both;float:left;width:460px;height:auto;'
                        }).setHTML('<style type="text/css">table.help { background-color:#F8F2D1;width:100%; border:1px solid #E0CA7C}table.help th {font-size:14px;font-style:italic;color:#888; background-color:#F7EDBD }table.help td { padding: 10px;background: #fff; }</style><table class="help"><tr><th>You Type:</th><th>You See:</th></tr>  <tr><td>===Heading===</td><td><h1>Heading 1</h1></td></tr><tr><td>***Heading***</td><td><h2>Heading 2</h2></td></tr><tr><td>[Click here to visit the About Us Page](/About_Us)</td><td><a href="/About_Us">Click here to visit the About Us Page</a></td></tr><tr><td>&lt;b&gt;This is important&lt/b&gt;</td><td><b>This is important</b></td></tr><tr><td>&lt;i&gt;"Difficulties mastered are opportunities won." - Winston Churchill&lt;/i&gt;</td><td><i>"Difficulties mastered are opportunities won." - Winston Churchill</i></td></tr><tr><td>He\'s &lt;u&gt;NOT&lt;/u&gt; the Messiah, He\'s a &lt;u&gt;very&lt;/u&gt; naughty boy!</td><td>He\'s <u>NOT</u> the Messiah, He\'s a <u>very</u> naughty boy!</td></tr><tr><td>[nolines]...[/nolines]</td><td>This removes all line breaks from output. Useful when inserting HTMl forms</td></tr></table>').injectAfter(divholder);
                    }
                }
            }
        }).injectInside(divholder);*/
                        
        new Element('input', {
            'type': 'button',
            'value': '-',
            'class': 'submitbutton',
            'style': 'margin:0;margin-left:60px;margin-right:4px;padding: 0',
            'title': 'Decrease EditBox Size',
            'events': {
                'click': function(form, el){
                    (new Event(form,el)).stop();
                    var h = input.getStyle('height').toInt();
                    var nh = h - 60;
                    if (nh <17) { nh = 17; }
                    var myH = new Fx.Style(input, 'height', {duration: 250}).start(h, nh);
                }
            }
        }).injectInside(divholder);
        
        new Element('input', {
            'type': 'button',
            'value': '+',
            'class': 'submitbutton',
            'style': 'padding: 0;margin:0;',
            'title': 'Increase EditBox Size',
            'events': {
                'click': function(form, el){
                    (new Event(form,el)).stop();
                    var h = input.getStyle('height').toInt();
                    var nh = h + 60;
                    var myH = new Fx.Style(input, 'height', {duration: 250}).start(h, nh);
                }
            }
        }).injectInside(divholder);

        // For every param, add a hidden input
        for (param in this.params) {
            new Element('input', {
                'type': 'hidden',
                'name': param,
                'value': this.params[param]
            }).injectInside(form);
        }

        //
        new Element('input', {
            'type': 'hidden',
            'name': 'id',
            'value': id
        }).injectInside(form);
        
        // inject our target
        new Element('input', {'type': 'hidden','name': 'target','value': target }).injectInside(form);

        // Add the form after the target element
        form.injectAfter(el);

        // Create a textarea or input for user
        var input = new Element('textarea', {
            'name': 'content',
            'class': 'editbox',
            'style': 'height: '+height,
            'id' : 'textbox-'+id
        }).appendText('Getting content from server...').injectInside(form);
        
        this.ajaxGet(id,input,target);
        
        oldstyles = input.getStyles('position','display','width','overflow','z-index');

        // Focus on the input
        //input.focus();
    },
    
    /**
     * Ajax Get
     * @param id to pass to php script
     * @param element to update with content
     */
    ajaxGet: function(id, el, target) {
        $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', 'true'); });
        el.setProperty('disabled', 'true');
        if (!el) { el = $('textbox'); }
        url = "?getcontent=1&id="+id+"&target="+target;
        var rq = new Ajax("/update.php"+url, {
            method: 'get',
            onComplete:function(resp){
                var content = resp;
                el.setText(resp);
                $$('form input.submitbutton').each(function(i, c) { i.setProperty('disabled', ''); });
                el.setProperty('disabled', '');
            }
        }).request();
    },

    /**
     * Hide form
     * @param element form Your target form.
     * @param element el Your target element.
     */
    hideForm: function(form, el) {
            form.addClass(this.options.hiddenCl);
            el.removeClass(this.options.hiddenCl);
    }

});



// needs to be domready instead of load for ie6
window.addEvent('load', Site.start);