/* Mootools effects */

//http://joliclic.free.fr/php/javascript-packer/en/index.php
// Initalise mainstay object
var mainstay = {
    
    changeBg: function() {
        if ($('chgbg')) {
            // first check for cookie
            var bgCookie = new Hash.Cookie('bg',{duration: 30, path: '/'});
            var cBg = bgCookie.get('num');
            if (cBg > 0 && cBg < 9) {
                $('chgbg').src = '/images/changebg'+cBg+'.png';
                $("background").setStyle("background-image", "url(/images/background"+cBg+".png)");
            } else { $('chgbg').src = '/images/changebg1.png'; }
            $('changebg').addEvent('click', function(e){
                e = new Event(e);
                var currentBg = $("background").getStyle("background-image");
                currentBg = currentBg.split('background');currentBg = currentBg[1];
                currentBg = currentBg.split('.png');currentBg = currentBg[0];
                newBg = currentBg;
                newBg++;
                if (newBg > 0 && newBg < 9) { newUrl = "url(/images/background"+newBg+".png)"; safeUrl = '/images/background'+newBg+'.png'; }
                else { newUrl = "url(/images/background1.png)";safeUrl = '/images/background1.png';newBg = 1; }
                // save cookie
                bgCookie.set('num',newBg);
                bgCookie.save();
                $('customiseload').setStyle('display', 'block');
                $('customiseload').setHTML('Loading Image '+newBg+'...');
                
                var images = [safeUrl];
                var mySlider = new Fx.Slide('margins', {duration: 1000, mode : 'horizontal'});
                var myStuff = new Fx.Style('background', 'opacity', {duration: 500}).addEvent('onComplete', function(){
                        mySlider.slideIn();
                        $('customiseload').setHTML('');
                        $('customiseload').setStyle('display', 'none');
                    });
                
                new Asset.image(safeUrl, {id: 'backgroundimg', title:safeUrl, onload: function() {
                    $('chgbg').src = '/images/changebg'+newBg+'.png';
                    $("background").setStyle("background-image", newUrl);
                    $('customiseload').setHTML('Complete!');
                    mySlider.slideOut();
                    myStuff.start.delay(1000, myStuff, [0.8,1]);
                    }
                });
                e.stop();
            });
        }
    },


    // makeSliders finds all slider layouts on the page and makes a slider for each one
    makeSliders: function() {
        // create sliders
        this.sliders = $$('div.section-content').map(function(div){
            return new Fx.Slide(div, {
                duration: 530,
                transition:Fx.Transitions.Back.easeInOut
            })//.hide();
        });
        
        // find all the section-content
        var pos = [];
        $$('a.section-header-right-image').each(function(lnk, index){
            var tid=index;tid++;
            pos[index] = "top";
            tid = "section" + tid + "-toggle";
            lnk.addEvent('click', function(e){
                e = new Event(e);
                this.sliders.each(function(slider, sliderIndex){
                    if (sliderIndex == index) {
                        this.sliders[sliderIndex].toggle();
                        if (pos[index] == "top") { pos[index] = "bottom"; } else { pos[index] = "top"; }
                        $(tid).setStyle('background-position', pos[index]);
                    }
                    e.stop();
                }, this);
            }.bind(this));
        }, this); // last each
    },
    
    makeKwicks : function() {
        //var szNormal = 193, szSmall  = 153, szFull   = 342;
        var szNormal = 175, szSmall  = 92, szFull   = 342;
    if ($('kwick')) {
        var kwicks = $$('#kwick .kwick');
            var fx = new Fx.Elements(kwicks, {wait: false, duration: 300, transition: Fx.Transitions.quadOut});
            kwicks.each(function(kwick, i){
                kwick.addEvent('mouseenter', function(e){
                    var obj = {};
                    obj[i] = {
                        'width': [kwick.getStyle('width').toInt(), szFull]
                    };
                    kwicks.each(function(other, j){
                        if (other != kwick){
                            var w = other.getStyle('width').toInt();
                            if (w != szSmall) obj[j] = {'width': [w, szSmall]};
                        }
                    });
                        fx.start(obj);
                });
            });
            $('kwick').addEvent('mouseleave', function(e){
                var obj = {};
                kwicks.each(function(other, j){
                    obj[j] = {'width': [other.getStyle('width').toInt(), szNormal]};
                });
                fx.start(obj);
            });
    }
    },
    
    fontChanger: function() {
        if ($('customise')) {
            /* fx morph */
            Fx.Morph = Fx.Styles.extend({
                start: function(className){
                    var to = {};
                    $each(document.styleSheets, function(style){
                        if (style.href != null) {
                            if (style.href.contains('mainstaystudent.co.uk') || style.href.contains('s.css')) {
                                //console.log(style.href);
                                var rules = style.rules || style.cssRules;
                                //console.log("stylesheet: " + style.href);
                                $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('edit', {wait: false});
        var myMorph = new Fx.Morph('edit', {wait: false});
        var fontsize = new Hash.Cookie('fs',{duration: 60});
        fs = fontsize.get('class');
        if (fs == 'fontbiggest') { myMorph.start('fontbiggestclass'); $('fontbiggest').setStyle('background-position', 'bottom'); }
        else if (fs == 'fontnormal') { myMorph.start('fontnormalclass'); $('fontnormal').setStyle('background-position', 'bottom'); }
        else if(fs == 'fontsmallest') { myMorph.start('fontsmallestclass'); $('fontsmallest').setStyle('background-position', 'bottom'); }
        
        if ($('fontbiggest') && $('fontnormal') && $('fontsmallest')) {
            $('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();
            });
        }
        }
    },
    
    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');
                    //var cFH = form.getParent().empty().addClass('ajax-loading');
                    var cFH = form.getParent().addClass('ajax-loading');
                    new Ajax(sz,{
                        postBody: form,
                        update: cFH,
                        onComplete: function(resp) {
                            cFH.removeClass('ajax-loading');
                        }
                    }).request();
                }
                //new Event(isPassed, form).stop();
            }});
            }
            else {
            }
        });
    },
    
    loginForm : function() {
        var loginForm = $('loginForm');
        if ($chk(loginForm)) {
            loginForm.addEvent('submit', function(e) {
                new Event(e).stop();
                var cFH = loginForm.getParent().addClass('ajax-loading');
                var lAjax = new Ajax('/login.php', {
                    postBody: loginForm,
                    onComplete: function(ret) {
                        if (ret == '1') {
                            // they've logged in
                            cFH.removeClass('ajax-loading');
                            cFH.setText('Login Successful... Reloading Page...');
                            mainstay.rebook();
                            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(loginForm);
                        }
                    }
                }).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-username', {
            errorMsg: 'The username has already been taken!',
            rv: false,
            test: function(el) {
                var onComplete = function(ret) {
                        if (ret == '0' || !ret) {
                            regFormValidator.hideAdvice('find-username', el);
                            regFormValidator.rv = true;
                        }
                        else if (ret == '1') {
                            regFormValidator.showAdvice('find-username', el);
                            regFormValidator.rv = false;
                        }
                };
                if (el.getValue() != '') {
                    new Ajax('/register.php', {method: 'get', postBody: 'checkuser='+el.getValue(), onComplete: onComplete.bind(regFormValidator)}).request();
                    return regFormValidator.rv;
                } else { return true; }
            }
        });
        // var ePrizeForm = $(form).getElementsBySelector('input, select, textarea, checkbox');
        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';
        });
    },
    
    imageDimensions : function() {
        // our image names are called dim
        $$('img.dim').each(function(image) {
            var msg = image.src + "\n\n" +
            "image.width: " + image.width + "\n" +
            "image.height: " + image.height + "\n\n" +
            "image.getProperty(width): " + image.getProperty('width') + "\n" +
            "image.getProperty(height): " + image.getProperty('height') + "\n";
            alert(msg);
        });
    },
    
    rebook: function() {
        if (!Cookie.get('seenRebook')) {
            window.open("/rebook/index.html",'_blank', 'height=640,left=75,location=0,resizable=1,toolbar=1,top=100,width=602,scrollbars=1',false);
            Cookie.set('seenRebook', 'yes', {duration: 3});
        }
    },
    pop: function(u, w, h) {
	window.open(u,'_blank', 'height='+h+',width='+w+'left=75,location=0,resizable=1,toolbar=0,top=100,scrollbars=1',false);
    },
    
    toolTips : function() {
        var myTips = new Tips($$('.toolTip'), {
        });
    },
    
    
    init: function() {
        this.makeSliders();
        this.makeKwicks();
        this.changeBg();
        this.fontChanger();
        this.createForms();
        this.regForm();
        this.loginForm();
        this.externalLinks();
        this.toolTips();
    }
};


window.onDomReady(mainstay.init.bind(mainstay));