/* my code */


var xenex = {
    morph : function() {
    /* fx morph */
        Fx.Morph = Fx.Styles.extend({
            start: function(className){
                var to = {};
                $each(document.styleSheets, function(style){
                    var rules = style.rules || style.cssRules;
                    $each(rules, function(rule){
                        if (!rule.selectorText.test('\.' + className + '$')) return;
                        Fx.CSS.Styles.each(function(style){
                                if (!rule.style || !rule.style[style]) return;
                                var ruleStyle = rule.style[style];
                                to[style] = (style.test(/color/i) && ruleStyle.test(/^rgb/)) ? ruleStyle.rgbToHex() : ruleStyle;
                        });
                    });
                });
                return this.parent(to);
            }
    });
    Fx.CSS.Styles = ["backgroundColor", "backgroundPosition", "color", "width", "height", "left", "top", "bottom", "right", "fontSize", "letterSpacing", "lineHeight", "textIndent", "opacity"];
    Fx.CSS.Styles.extend(Element.Styles.padding);
    Fx.CSS.Styles.extend(Element.Styles.margin);
    Element.Styles.border.each(function(border){
        ['Width', 'Color'].each(function(property){
            Fx.CSS.Styles.push(border + property);
        });
    });    
    },
    
    
    doEdit : function() {
        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';
            
            
            // 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;

            // 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(form);
            

            // Add a cancel button
            new Element('input', {
                'type': 'button',
                'value': 'cancel',
                'class': 'submitbutton',
                'events': {
                    'click': function(form, el){
                        obj.hideForm(form, el);
                        //alert("form: "+form+" el: "+el);
                        //(new Event(form,el)).stop();
                    }.pass([form, el])
                }
            }).injectInside(form);
            
            var big = 0;
            var oldstyles;
            new Element('input', {
                'type': 'button',
                'value': '<->',
                'class': 'submitbutton',
                '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 = $('container').getStyle('width').toInt();
                            input.setStyles({
                            'position': 'absolute',
                            'display': 'block',
                            'left': '-4px',
                            '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(form);
            
            new Element('input', {
                'type': 'button',
                'value': '-',
                'class': 'submitbutton',
                'style': 'margin:0;margin: 0 5px 0 5px; 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(form);
            
            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(form);

            // 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',
                '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);
	}

        });
        new eip( $$('#contentholder .textholder'), '/update.php', {update: '1', updatecontent: '1'});
    },
    
    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();
                    }
                }});
            //}
        });
    },
    
    loginForm : function() {
        var myloginForm = $('loginForm');
        if ($chk(myloginForm)) {
            myloginForm.addEvent('submit', function(e) {
                new Event(e).stop();
                var cFH = myloginForm.getParent().addClass('ajax-loading');
                if (!window.ie6) var redirect = myloginForm.redirect.getValue();
                if (window.ie6) {var redirect = loginForm.redirect.value;}
                var lAjax = new Ajax('/login.php', {
                    postBody: myloginForm,
                    onComplete: function(ret) {
                        if (ret == '1') { // they've logged in
                            cFH.removeClass('ajax-loading');
                            cFH.setText('Login Successful... Reloading Page...');
                            if(redirect) { window.location = '/'+redirect; }
                            else { window.location = self.location; }
                        } else if (ret == '0') { // login unsuccessful
                            if ($chk($('loginErrorMsg'))) $('loginErrorMsg').remove();
                            var errorMsg = new Element('div', {
                                'id': 'loginErrorMsg',
                                'styles': {
                                    'color': 'red',
                                    'font-weight': 'bold',
                                    'text-align': 'center'
                                }
                            }).appendText('Login Unsuccessful, please try again');
                            cFH.removeClass('ajax-loading');
                            cFH.setStyle('background-color', '#FF0720');
                            var myMorph = new Fx.Morph(cFH, {wait: false});
                                myMorph.start('rightnorm');
                            errorMsg.injectBefore(myloginForm);
                        }
                    }
                }).request();
            });
        }
    },
    
    regForm : function() {
        var regFormValidator = new FormValidator($('regForm'), {onFormValidate: function(isPassed, form) {
            if (isPassed == true) {
                var cFH = form.getParent().addClass('ajax-loading');
                var myAjax = new Ajax('/register.php',{
                    method: 'post',
                    postBody: $('regForm'),
                    update: cFH,
                    onComplete: function(resp) {
                        cFH.removeClass('ajax-loading');
                    }
                }).request();
            }
        }});
        regFormValidator.add('find-email', {
            errorMsg: 'The email address has already been taken!',
            rv: false,
            test: function(el) {
                var onComplete = function(ret) {
                    if (ret == '0' || !ret) {
                        this.hideAdvice('find-email', el);
                        regFormValidator.rv = true;
                    }
                    else if (ret == '1') {
                        this.showAdvice('find-email', el);
                        regFormValidator.rv = false;
                    }
                };
                new Ajax('/register.php', {method: 'get', postBody: 'checkemail='+el.getValue(), onComplete: onComplete.bind(regFormValidator)}).request();
                return regFormValidator.rv;
            }
        });
    },
    
    externalLinks : function() {
        $$('a.external').each(function(link) {
            link.target = '_blank';
        });
    },
    
    copyForm : function() {
        var copyForm = $('copyForm');
        if ($chk('copyForm')) {
            var cost = 0;
            var inputs = {'press_release' : 95, 'product_story' : 75, 'editorial_feature_article' : 250, 'advertorial' : 250, 'application_story' : 300};
            $$('input.cnt').each( function(i) {
                // duplicate event funtionality here for page load
                if (i.getProperty('checked') == true) { cost += inputs[i.getProperty('name')]; }
                $('total_cost').setHTML("<b>&pound;"+cost+" + VAT</b>");
                i.addEvent('click', function(e) {
                    if (i.getProperty('checked') == true) { cost += inputs[i.getProperty('name')]; }
                    else if(i.getProperty('checked') == false) { cost -= inputs[i.getProperty('name')]; }
                    $('total_cost').setHTML("<b>&pound;"+cost+" + VAT</b>");
                });
            });
        }
        if ($chk(copyForm)) {
            copyForm.addEvent('submit', function(e) {
            var formParent = $('copyForm').getParent().addClass('ajax-loading2');
            formParent.appendText('Please be patient while the form is submitted. Large attachments can take a couple of minutes to transfer');
            });
        }
    },
    
    premiumForm : function() {
        var premiumForm = $('premiumForm');
        if ($chk('premiumForm')) {
            var cost = 0;
            var inputs = {'press_release' : 175, 'product_story' : 125, 'editorial_feature_article' : 325, 'advertorial' : 325, 'application_story' : 375};
            $$('input.cntp').each( function(i) {
                // duplicate event funtionality here for page load
                if (i.getProperty('checked') == true) { cost += inputs[i.getProperty('name')]; }
                $('total_cost').setHTML("<b>&pound;"+cost+" + VAT</b>");
                i.addEvent('click', function(e) {
                    if (i.getProperty('checked') == true) { cost += inputs[i.getProperty('name')]; }
                    else if(i.getProperty('checked') == false) { cost -= inputs[i.getProperty('name')]; }
                    $('total_cost').setHTML("<b>&pound;"+cost+" + VAT</b>");
                });
            });
        }
        if ($chk(premiumForm)) {
            premiumForm.addEvent('submit', function(e) {
            var formParent = $('premiumForm').getParent().addClass('ajax-loading2');
            formParent.appendText('Please be patient while the form is submitted. Large attachments can take a couple of minutes to transfer');
            });
        }
    },
    
    toolTips : function() {
        var myTips = new Tips($$('.toolTip'), {
            offsets: {'x': 75, 'y': 0}
        });
    },
    
    accord : function() {
        if ($chk('accordion')) {
            var accordion = new Accordion('h3.atStart', 'div.atStart', {
                opacity: false,
                onActive: function(toggler, element){
                        if (toggler.hasClass('done')) toggler.setStyle('color', '#DDEEC2');
                        else toggler.setStyle('color', '#ff3300');
                },
         
                onBackground: function(toggler, element){
                        toggler.setStyle('color', '#222');
                }
            }, $('accordion'));
        }
    },
    
    doneForms : function() {
        var ajaxForms = $$('.doneForm');
	ajaxForms.each(function(forms, i){
            forms.isDone.addEvent('click', function(e){
                var sz = forms.getProperty('action');
                var myAjax = new Ajax(sz,{
                    postBody: forms,
                    onComplete: function(resp) {
                        if (resp == 1) {
                            var par = forms.getParent().getParent();
                            var parnext = par.getNext();
                            par.addClass('done'); par.setStyle('color', '#DDEEC2');
                            parnext.addClass('donesub');
                        }
                        else {
                            var par = forms.getParent().getParent();
                            var parnext = par.getNext();
                            par.removeClass('done'); par.setStyle('color', '#ff3300');
                            parnext.removeClass('donesub');
                        }
                    }
                }).request();
            });
        });
    },
    
    fontChanger: function() {
        /* fx morph */
        Fx.Morph = Fx.Styles.extend({
            start: function(className){
                var to = {};
                $each(document.styleSheets, function(style){
                    var rules = style.rules || style.cssRules;
                    $each(rules, function(rule){
                        if (!rule.selectorText.test('\.' + className + '$')) return;
                        Fx.CSS.Styles.each(function(style){
                                if (!rule.style || !rule.style[style]) return;
                                var ruleStyle = rule.style[style];
                                to[style] = (style.test(/color/i) && ruleStyle.test(/^rgb/)) ? ruleStyle.rgbToHex() : ruleStyle;
                        });
                    });
                });
                return this.parent(to);
            }
    });
    Fx.CSS.Styles = ["backgroundColor", "backgroundPosition", "color", "width", "height", "left", "top", "bottom", "right", "fontSize", "letterSpacing", "lineHeight", "textIndent", "opacity"];
    Fx.CSS.Styles.extend(Element.Styles.padding);
    Fx.CSS.Styles.extend(Element.Styles.margin);
    Element.Styles.border.each(function(border){
        ['Width', 'Color'].each(function(property){
            Fx.CSS.Styles.push(border + property);
        });
    });
    var myMorph = new Fx.Morph('textholder', {wait: false});
    var fontsize = new Hash.Cookie('fs',{duration: 60});
    fs = fontsize.get('class');
    if (fs == 'fontbiggest') { myMorph.start('fontbiggestclass');}
    else if (fs == 'fontnormal') { myMorph.start('fontnormalclass');}
    else if(fs == 'fontsmallest') { myMorph.start('fontsmallestclass');}
    
    $('fontbiggest').addEvent('click', function(e){
            fontsize.set('class','fontbiggest');
            fontsize.save();
            myMorph.start('fontbiggestclass');
            //$('fontbiggest').setStyle('background-position', 'bottom');$('fontnormal').setStyle('background-position', 'top');$('fontsmallest').setStyle('background-position', 'top');
            new Event(e).stop();
    });
    $('fontnormal').addEvent('click', function(e){
            fontsize.set('class','fontnormal');
            fontsize.save();
            myMorph.start('fontnormalclass');
            //$('fontnormal').setStyle('background-position', 'bottom');$('fontbiggest').setStyle('background-position', 'top');$('fontsmallest').setStyle('background-position', 'top');
            new Event(e).stop();
    }); 
    $('fontsmallest').addEvent('click', function(e){
            fontsize.set('class','fontsmallest');
            fontsize.save();
            myMorph.start('fontsmallestclass');
            //$('fontsmallest').setStyle('background-position', 'bottom');$('fontbiggest').setStyle('background-position', 'top');$('fontnormal').setStyle('background-position', 'top');
            new Event(e).stop();
    });
    },
    
    init : function() {
        this.morph();
        this.doEdit();
        this.createForms();
        this.loginForm();
        this.regForm();
        this.copyForm();
        this.premiumForm();
        this.toolTips();
        this.accord();
        this.doneForms();
        this.fontChanger();
    }
};


window.onDomReady(xenex.init.bind(xenex));