/***
Handles the top contact form.
 ***/
var contactForm = {
	open: false,
    label: "Contact Number",
	init: function() {
		this.block = $('contact-us');
        this.form = this.block.getElement('form');
        
        if (this.form != null) {
            this.form.addEvent('submit',
                    contactForm.form_submit.bind(contactForm)
                    );
            this.visible_fieldset = this.form.getElement('fieldset').getFirst();
            this.visible_fieldset.show();
            this.hidden_fieldset = this.form.getElement('fieldset.pre-hidden');

            this.phone_input = $('id_phone_number');
            this.phone_input.set('value', this.label);
            
            this.phone_input.addEvent('focus', 
                        contactForm.phone_input_onfocus.bind(contactForm)
                    );
            this.phone_input.addEvent('blur', 
                        contactForm.phone_input_onblur.bind(contactForm)
                    );
            this.cancel_button = $('close-callback-button')
            this.cancel_button.addEvent('click',
                        contactForm.hide.bind(contactForm)
                    );
            this.errors = $$('#contact-us ul.errorlist');
            if (this.errors.length) { this.show(); }
        }
	},
	show: function() {
		this.hidden_fieldset.show();
		this.open = true;
	},
	hide: function() {
		this.errors.dispose();
		this.hidden_fieldset.hide();
		this.open = false;
		return false;
	},
    form_submit: function() {
        if (this.phone_input.get('value') == this.label) {
            this.phone_input.set('value', '');    
        }
    },
    phone_input_onfocus: function() {
        this.show();
        if (this.phone_input.get('value') == this.label) {
            this.phone_input.set('value', '');    
        }
    },
    phone_input_onblur: function() {
        if (this.phone_input.get('value') == '') {
            this.phone_input.set('value', this.label);
        }
    }
};

/**
Handles the feedback reloading
 ***/

FEEDBACK_CURRENT = 0;

var feedback = {
    setup: function(){
        var simple_content = $('feedbacksimplecontent');
        this.franchise = simple_content.get('rel');
        this.container = new Element('ul');
        this.container.inject(simple_content);
        var button = new Element('li', {
                'class': 'feedback-button'
            });
        button.inject(this.container, 'bottom');
        var href = new Element('a', {
                href: '/about-aspect/customer-reviews/',
                'class': 'reload-button',
                html: 'More feedback'
            });
        href.inject(button, 'top');
    },
    init: function(){
        // Do not execute if feedback is not there
        if(!$('feedbacksimplecontent')){return false;}
        this.setup();
        this.do_request();
    },
    do_request: function(){
        var url = '/api/latest-feedback/';
        if (this.franchise != null) {
            url = url + this.franchise + '/';
        }
        jsonrequest = new Request.JSON({
                url: url,
                onSuccess: function(list){
                    list.each(function(e){
                            // Geez, All this pointless markup is due microformats
                            var li = new Element('li', {
                                    'class': 'hreview feedback-item'
                                });
                            li.inject(this.container, 'top');
                            var p = new Element('p', {
                                   'class': 'reviewer vcard'
                                });
                            p.inject(li, 'top');
                            var fn = new Element('span', {
                                    'class': 'fn',
                                    html: e.name + ', '
                                });
                            fn.inject(p, 'top');
                            var addr = new Element('span', {
                                    'class': 'postcode',
                                    html: e.location
                                });
                            addr.inject(p, 'bottom');
                            var summary = new Element('p', {
                                    'class': 'summary',
                                    html: e.body
                                });
                            summary.inject(li, 'bottom');
                        }.bind(this));
                    this.animate();
                }.bind(this)
            }).get();
    },
    animate: function(){
        var offset = 100;
        items = $$(".feedback-item");
        if(items.length > 0){                       // display the first item
            items[0].setStyles({display: 'block'});
        }
        // add action to the button
        // buttons = $$(".feedback-button");
        // buttons.addEvent('click', function(event){
                // event.stop();
                // feedback_next = FEEDBACK_CURRENT + 1;
                // if(feedback_next >= items.length){
                    // feedback_next = 0;
                // }
                // items[FEEDBACK_CURRENT].setStyle('display', 'none');
                // items[feedback_next].setStyles({display: 'block'});
                // FEEDBACK_CURRENT = feedback_next;
            // });
    }
};


/***
Handles the animation of the masthead
 ***/
MASTHEAD_CURRENT = 0;

function masthead_reset_links(){
    // removes the on button from all links
    var masthead_items = $$('.masthead-item-anchor');
    masthead_items.each(function(item){
            item.removeClass('on');
        });
}

var masthead_movement = function(){
    MASTHEAD_CURRENT++;
    if(MASTHEAD_CURRENT >= MASTHEAD_LIST.length){
        MASTHEAD_CURRENT = 0;
    }
    // remove all on buttons
    masthead_reset_links();
    // show the on button
    var anchor_id = 'anchor-' + MASTHEAD_CURRENT;
    $(anchor_id).addClass('on');
    var masthead_items = $$('.masthead-item');
    var back = $('masthead-bg-holder');
    var front = $('masthead-bg-transition');
    // previous bg at the front
    var masthead_previous = MASTHEAD_CURRENT - 1;
    if(masthead_previous < 0){
        masthead_previous = MASTHEAD_LIST.length - 1;
    }
    front.setStyle('background-image', 'url('+ MASTHEAD_LIST[masthead_previous] +')');
    // current bg at the back
    back.setStyle('background-image', 'url('+ MASTHEAD_LIST[MASTHEAD_CURRENT] +')');
    var mastheadTween = new Fx.Morph(front, {duration: '1000',
                                             transition: Fx.Transitions.Sine.easeOut }
        );
    mastheadTween.set({'opacity': '1'});
    mastheadTween.start({'opacity': '0'});
};


BG_WIDTH = 975;
BG_HEIGHT = 220;

var masthead = {
    addCustomEvent : function(){
        // adds click event to the controls
    },

    addHtml : function(){
        // adds holder for the background
        $$('.tagline').setStyle('position','relative');
        $$('#header p.logo').setStyle('position','relative');
        $('header').setStyles({
                height: BG_HEIGHT,
                background: 'none',
                position: 'relative'
            });
        var div_holder = new Element('div').set({'id': 'masthead-bg-holder'
            }).inject('header','top');
        div_holder.setStyles({width: BG_WIDTH,
                    height: BG_HEIGHT,
                    'background-image': 'url('+ MASTHEAD_LIST[MASTHEAD_CURRENT] +')',
                    position: 'absolute',
                    margin: 0,
                    padding: 0,
                    top: 0,
                    left: 0
                    });
        var div_transition = new Element('div').set({'id': 'masthead-bg-transition',
                                                     'html': '&nbsp;'
            }).inject('masthead-bg-holder');
        div_transition.setStyles({width: BG_WIDTH,
                    height: BG_HEIGHT,
                    'background-image': 'url('+ MASTHEAD_LIST[MASTHEAD_CURRENT] +')',
                    margin: 0,
                    padding: 0,
                    top: 0,
                    left: 0
                    });
        // adds the control for the header
        ul = new Element('ul');
        ul.addClass('masthead-controls clearfix relative');
        // Add the default one
        for(var i=0; i<MASTHEAD_LIST.length; i++){
            // Add the elements in the list
            li = new Element('li').addClass('masthead-item').inject(ul);
            anchor = new Element('a').inject(li).set({'html':'.',
                                                      'id': 'anchor-'+i,
                                                      'class':'masthead-item-anchor replaced'});
        }
        ul.inject('header');
    },

    init : function(){
        var self = this;
        self.addHtml();
        // on button for the first element
        var anchor_id = 'anchor-' + MASTHEAD_CURRENT;
        $(anchor_id).addClass('on');
        var masthead_transition = masthead_movement.create({periodical: 12000});
        masthead_transition();
    }


};

/***
Handles the areas at the bottom
***/

var locale_areas  = {
    init: function(){
        var locale_copy = $('locale-copy');
        if(locale_copy){
        var locale_anchor = new Element('a').inject(locale_copy).set({'html':'Click here for postcodes',
                                                                      'href': '#',
                                                                      'id': 'locale-anchor'});
        reveal_animation = new Fx.Reveal($('london-areas'), {duration: 500,
                                                             mode: 'horizontal',
                                                             transition: Fx.Transitions.Sine.easeIn});
        reveal_animation.dissolve();
        locale_anchor.addEvent('click', function(event){
                event.stop();
                reveal_animation.reveal();
            });
        }
    }
};

/***
Handles the latest jobs ticker
***/

var latest_jobs = {
    setup: function(){
        this.latest = $('latest-works-container');
        this.list_container = new Element('ul');
        this.latest.adopt(this.list_container);
    },
    init: function(){
        // Do not execute if latest works aren't there
        if(!$('latest-works-container')){return false;}
        if(!('latest' in this)){
            // execute the setup and json call  only once
            this.setup();
            this.do_request();
        }
    },
    do_request: function(){
        jsonrequest = new Request.JSON({
                url: '/api/latest-jobs/',
                onSuccess: function(list){
                    list.each(function(e){
                            // create element
                            var item_em = new Element('em', {html: e.location});
                            var item = new Element('li', {html: '&hellip; '+ e.body});
                            item_em.inject(item, 'top');
                            // inject it into the list
                            item.inject(this.list_container, 'bottom');
                        }.bind(this));
                    this.animate();
                }.bind(this)
            }).get();
    },
    animate: function(){
        var latestFx = new Fx.Scroll(this.latest, {duration: 65000,
                                                   transition: Fx.Transitions.linear
            }).toBottom().chain(function(){
                    var content_copy = this.list_container.clone();
                    content_copy.inject(this.list_container, 'after');
                    this.list_container = content_copy;
                    this.animate();
                }.bind(this));
    }
};


/***
Handles areas we cover ticker
TODO: create a plugin with this animation
***/

var areas_covered = {
    init: function(){
        this.areas = $('areas-covered-container');
        // Do not execute if areas are not there
        if(!this.areas){return false;}
        this.list_container = this.areas.getElement('ul');
        this.animate();
    },
    animate: function(){
        var areasFx = new Fx.Scroll(this.areas, {duration: 290000,
                                                 transition: Fx.Transitions.linear
            }).toBottom().chain(function(){
                    var content_copy = this.list_container.clone();
                    content_copy.inject(this.list_container, 'after');
                    this.list_container = content_copy;
                    this.animate();
                }.bind(this));
    }
};

/********************
New pop up windows

var popup = {
    init: function(){
        var elements = $$('a[rel=external]');
        elements.addEvent('click', function(e){
                new Event(e).stop();
                var url = this.getProperty('href');
                var openPopup = new Browser.Popup(url ,{
                        width: 1024,
                        height: 768,
                    });
            });
    }
};
 ******************/

/***
Feedback form
***/

var feedback_form = {
    init: function(){
        // get the appropriate lists
        widget_list = $$('#job_feedback div.rating');
        widget_list.each(function(element){
                //element.setStyle('display', 'none');
                var input = element.getElement('input');
                var input_id = input.getAttribute('name') + '_widget';
                var widget_container = new Element('div', {
                        'class': 'feedback-widget',
                        'id': input_id
                    });
                var widget_handlers = element.getElements('input');
                widget_handlers.each(function(el){
                        var handler = new Element('a', {
                               'html': el.value,
                                'href': '#',
                                'class': 'feedback-handler'
                            });
                        // mark selected widgets
                        if(el.checked){
                            handler.addClass('selected');
                        }
                        handler.inject(widget_container, 'bottom');
                    });
                widget_container.inject(element, 'bottom');
                var a_elements = widget_container.getElements('a');
                a_elements.addEvent('click', function(event){
                        event.stop();
                        // deselect all of them
                        a_elements.removeClass('selected');
                        // select the current one
                        this.addClass('selected');
                        var parent = this.getParent();
                        // mark current value
                        var field_id = parent.getAttribute('id').replace('_widget', '');
                        var score = this.get('html');
                        var selector = 'input[name='+field_id+']';
                        var input_list = $$(selector);
                        input_list.each(function(input){
                                if(input.value == score){
                                    input.checked = true;
                                }
                            });
                    });
            });
    }
};

/***
Social network tabs
***/
var socialNetworkTabs = {
					
	init: function() {
		
		var container = $('social');
		if (!container) {return false;}
		
		this.tabs = container.getElements('ul.tabs a').addEvent('click', function(e) {
			this.switchTab(e);
			return false;
		}.bind(this))
		
		this.tabs[0].addClass('selected');
		
		this.panels = container.getElements('div#news-alerts, div#facebook, div#twitter'); //.filter('facebook').setStyle('display', 'none');
		container.getElements('div#facebook, div#twitter').setStyle('display', 'none');
	},
	switchTab: function(e) {
		this.panels.setStyle('display', 'none');
		this.tabs.removeClass('selected');
		e.target.addClass('selected');
		$(String.split(e.target.hash, '#')[1]).setStyle('display', 'block');
	}
}


// focus / blur input labels
var dwDefaults = new Class({
	//implements
	Implements: [Options],

	//options
	options: {
		collection: $$('input[type=text]')
	},
	
	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		this.defaults();
	},
	
	//a method that does whatever you want
	defaults: function() {
		this.options.collection.each(function(el) {
			el.set('value',el.get('rel')).addClass('blur');
			el.addEvent('focus', function() { if(el.get('value') == el.get('rel')) { el.set('value','').removeClass('blur'); } });
			el.addEvent('blur', function() { if(el.get('value') == '') { el.set('value',el.get('rel')).addClass('blur'); } });
		});
	}
	
});

window.addEvent('domready', function() {
	$$('body').addClass('jsenabled'); // Enables css when js is enabled
    contactForm.init();
	feedback.init();
	// masthead.init();
	locale_areas.init();
	latest_jobs.init();
    feedback_form.init();
    areas_covered.init();
	socialNetworkTabs.init();
	var defs = new dwDefaults({
		collection: $$('input.defs')
	});
});

