
/*global jQuery */

/*  This is where the magic happens, like on Cribs, except nothing quite
    so vile as that monstrous edifice.
 */

(function ($, window, document) {

    /*  Is any of this actually going to work?
     */

    if (typeof jQuery === 'undefined') {
        return null; // Hot Christ! jQuery isn't available! ABORT!
    }



    /*  Global damn variables - alphabetical order so no one gets jealous.
     */

    var body,           //  <body> element
        counties_pos,   //  Coordinates of each "state" of the county map in the website's header
        head,           //  <head> element
        html,           //  <html> element
        language,       //  The HTML lang attribute
        root,           //  The DOM document wrapped in a jQuery object
        text,           //  The set of translations to store based on the user's language preference
        translations;   //  Translation table used between many of these damn function



    /*  Instantiate just ONE jQuery object, use this to find other elements
        rather than creating a new jQuery object for each selector.
     */

    root = new $.prototype.init(document);



    /*  Any of them variables up there need setting?
     */

    translations = {
        en: {
            brother:         'Oh brother!',
            close_this:      'Close This',
            comment_posted:  'Your Comment Has Been Posted',
            comment_success: 'Your comment was successfully submitted and is awaiting approval. It will appear here once it has been moderated.',
            crikey:          'Crikey',
            like_login:      'You can\'t like a comment if you\'re not logged in!',
            no_message:      'Oh no! There isn\'t a message to display!',
            oh_dear:         'Oh dear.. That didn\'t quite work as planned..',
            photo:           'Photo',
            switch_vote:     'Switch your vote',
            thanks_help:     'Thanks for your help!',
            thanks_like:     'Thank you for liking this comment!',
            video:           'Video',
            voted:           'You voted for this band!',
            voted_unews:     'You voted for this story!',
            went_wrong:      'Something went wrong while we were submitting your comment. Check these errors and try again!',
            what_is_this:    'What is this?',
            you_like:        'You Like This'
        },

        cym: {
            brother:         'O Na!',
            close_this:      'Caewch Hwn',
            comment_posted:  'Postiwyd eich Sylw',
            comment_success: 'Cyflwynwyd eich sylwín llwyddiannus ac maeín disgwyl am ei gymeradwyo. Bydd yn ymddangos yma wedi iddo gael ei safoni.',
            crikey:          'O diar',
            like_login:      'Ni allwch roi sylw os nad ydych wedi logio i mewn!',
            no_message:      'O na! Does dim neges iíw harddangos!',
            oh_dear:         'O diar... Doedd hynína ddim wedi gweithio fel y dylai..',
            photo:           'Ffotograffau',
            switch_vote:     'CYM - Switch your vote',
            thanks_help:     'Diolch i chi am eich cymorth!',
            thanks_like:     'Diolch i chi am hoffiír sylw hwn!',
            video:           'Fideo',
            voted:           'You voted for this band!',
            voted_unews:     'You voted for this story!',
            went_wrong:      'Aeth rhywbeth oíi le pan oeddech yn cyflwyno eich sylw. Gwiriwch y gwallau hyn a rhowch gynnig arall arni!',
            what_is_this:    'Beth yw hwn?',
            you_like:        'Rydych yn Hoffi Hwn'
        }
    };

    counties_pos = {
        start:           0,
        anglesey:        242,
        blaenau:         484,
        bridgend:        726,
        caerphilly:      968,
        cardiff:         1210,
        carmarthenshire: 1452,
        ceredigion:      1694,
        conwy:           1936,
        denbighshire:    2178,
        flintshire:      2420,
        gwynedd:         2662,
        merthyr:         2904,
        monmouthshire:   3146,
        neath:           3388,
        newport:         3630,
        pembrokeshire:   3872,
        powys:           4114,
        rhondda:         4356,
        swansea:         4598,
        torfaen:         4840,
        vale:            5082,
        wrexham:         5324
    };



    /*  Plain old JavaScript functions should go here, or else JSLint will
        kick OFF and throw errors about like ninja stars or whatever.
     */

    function map_highlight(county) {

        var county_pos = (0).toString();

		if (county) {
			county_pos = county.split('-')[0];
		}

		body.find('.county_map img').css({
			backgroundPosition : '-' + counties_pos[county_pos] + 'px -300px'
		});

		body.find('.counties_list a').removeClass('hover');
		body.find('.counties_list .' + county + ' a').addClass('hover');

	}



    /*	Hey buddy I got your custom jQuery methods right here...
     */

	//	Build and Trigger qTip
	$.prototype.buildAndTriggerQtip = function (settings) {

        var config = {
            titleContent : 'No flippin\' message!',
			styleType : 'red'
        };

        if (settings) {
            config = $.extend(config, settings);
        }

	    this.each(function () {

			var qtip_config = {
				position: {
					corner: {
						target: 'topMiddle',
						tooltip: 'bottomMiddle'
					}
				},
				hide: {
					delay: 3000,
					when: {
						event: 'inactive'
					}
				},
				show: {
					when: {
						event: 'focus'
					}
				},
				style: {
					border: {
						radius: 5,
						width: 5
					},
					name: config.styleType,
					tip: {
						corner: 'bottomMiddle',
						size: {
							x: 8,
							y: 6
						}
					}
				},
				text: false
			};

			$(this)
				.attr('title', config.titleContent)
				.qtip(qtip_config)
				.trigger('focus')
				.trigger('blur');

		});

        return this;

	};



	//	Post Comments With Ajax
	$.prototype.postWithAjax = function (settings) {

        var config = {};

        if (settings) {
            config = $.extend(config, settings);
        }

		this.each(function () {

			var form = $(this);

			form.append('<input name="ajax" type="hidden" value="true" />');

			form.bind('submit', function (event) {
			        event.preventDefault();

                    if (body.find('.alert.error').length) {
                        body.find('.alert.error').slideUp(500, function () {
                            $(this).remove();
                        });
                    }

                    $.when($.ajax({
                        url: form.attr('action'),
                        data: form.serialize(),
                        dateType: config.type,
                        type: 'POST'
                    })).then(function (data) {

                        data = $.parseJSON(data);

                        switch (data.status) {
                        case 'win':

                            form.find('button').fadeOut();

                            form.find('textarea').fadeOut(250, function () {
                                $(this).remove();

                                var success_message = '<div class="alert done"><h3>' + text.comment_posted + '</h3><p>' + text.comment_success + '</p></div>';

                                $(success_message).css({ display : 'none' }).prependTo('.textarea_holder').slideDown();
                            });

                            break;

                        case 'fail':

                            var error_message, i, field, error;

                            error_message = '<div class="alert error">';
                            error_message += '<h3>' + text.crikey + '</h3>';
                            error_message += '<p>' + text.went_wrong + '</p>';
                            error_message += '<ul>';

                            for (i = data.errors.length - 1; i < data.errors.length; i += 1) {
                                field = data.errors[i].field;
                                error = data.errors[i].error;

                                $('#' + field).addClass('error');

                                error_message += '<li>' + error + '</li>';
                            }

                            error_message += '</ul>';
                            error_message += '</div>';

                            $(error_message).css({ display : 'none' }).prependTo('.textarea_holder').slideDown();

                            break;
                        }

                    });
                    
                });

		});

        return this;

	};



	//	Increase a comment's "like" count with Ajax, doesn't it?
	$.prototype.likeCommentWithAjax = function () {

		this.bind('click', function (event) {

		    event.preventDefault();

			var like_link = $(this);

			$.when($.ajax({
			    url: like_link.attr('href'),
			    data: { ajax : true },
			    type: 'GET',
			    dataType: 'json'
			})).then(function (data) {

				if (data.status === 'win') {

					var like_count    = like_link.parent().find('.like_count'),
					    current_count = parseInt(like_count.text(), 10);

					like_count
						.text(current_count + 1)
						.buildAndTriggerQtip({
							titleContent : text.thanks_like,
							styleType : 'green'
						});

					like_link.replaceWith('<span>' + text.you_like + '</span>');

				} else {

					like_link.buildAndTriggerQtip({
						titleContent : text.like_login,
						styleType : 'red'
					});

				}

			});

		});

        return this;

	};



	//	Report Abuse and that
	$.prototype.reportAbuseWithAjax = function () {

		this.one('click', function (event) {

		    event.preventDefault();

			var link = $(this);

			$.when($.ajax({
			    url: link.attr('href'),
			    data: { ajax : true },
			    type: 'GET',
			    dataType: 'json'
			})).then(function (data) {

				if (data.status === 'win') {

					link.buildAndTriggerQtip({
						titleContent : text.thanks_help,
						styleType : 'green'
					});

				} else {

					link.buildAndTriggerQtip({
						titleContent : text.oh_dear,
						styleType : 'red'
					});

				}

			});

			link.removeAttr('href');

		});

        return this;

	};



	//	Multi Images
	$.prototype.multiImages = function () {

	    this.each(function () {

			var container = $(this),
			    images    = container.find('ul.full li:not(.video) img');

			$('<ul class="clearfix thumbs"></ul>').insertAfter('ul.full');

			body.find('ul.full li.video').each(function () {

				if (images.length > 0) {
					$('<li class="video"><a href="#"><img src="/incs/themes/common/img/icons/video.png" alt="" /></a></li>').appendTo('ul.thumbs');
				}

			});

			if (images.length > 0 || body.find('ul.full li.video').length) {

				images.each(function () {

					var image     = $(this),
                        image_src = image.attr('src'),
                        src_array = image_src.split('/'),
                        filename  = src_array[src_array.length - 1];

					$('<li><a href="#"><img src="/img/thumbs/' + filename + '" alt="" /></a></li>').appendTo('ul.thumbs');

				});

			}

			body.find('.full').cycle({
				speed: 250,
				timeout: 0,
				pager: '.thumbs',
				pagerAnchorBuilder: function (idx) {

					return '.thumbs li:eq(' + idx + ') a';

				}
			});

		});

        return this;

	};



	//	BG Position Picker
	$.prototype.bgPosPicker = function () {

		this.each(function () {

		    var bg_pos = $(this);

			bg_pos.find('input:checked').closest('li').addClass('checked');

			bg_pos.find('li').bind('click', function (event) {

			    event.preventDefault();

				bg_pos.find('input').removeAttr('checked');
				bg_pos.find('li.checked').removeClass('checked');

				$(this)
					.addClass('checked')
					.find('input')
					.attr('checked', 'checked');

			});

		});

        return this;

	};



	//	Network Banner Map
	$.clicmap = function () {

		var map_src = '/incs/themes/common/img/network_banner/county_map_js.png';

		$('<img />', {
		    src: '/incs/themes/common/img/network_banner/network_hanger.png'
		});

		$('<img />', {
		    src: '/incs/themes/common/img/network_banner/county_hanger.png'
		});

		$('<div/>', {
		    'class': 'hanger_close',
		    text: text.close_this
		}).appendTo('.hanger').bind('click', function (event) {
		    event.preventDefault();
			$(this).parent().hide();
		});

		body.find('.hanger_open').bind('click', function (event) {

		    event.preventDefault();

			var hanger = '.' + $(this).attr('id');

			body.find('.hanger').hide();

			if ($(this).attr('id') !== 'county_picker') {
				body.find(hanger).css({
					left: ($(this).position().left - 10)
				});
			}

			body.find(hanger).show();

		});

		$('<img />', {
		    src: map_src,
		    load: function () {

                body.find('.county_map').css('background-image', 'url(' + map_src + ')');

                if (body.find('a.current_site').length) {
                    var current_county = body.find('a.current_site').parent().attr('id').split('-')[0];

                    if (body.find('a.current_site').length) {
                        body.find('.county_map').css('background-position', '-' + counties_pos[current_county] + 'px 0');
                    }
                }

				body.find('.county_map img')
					.attr('src', '/incs/themes/common/img/network_banner/trans.png')
					.css('background-image', 'url(' + map_src + ')');

				body.find('map#counties area').bind({
				    mouseenter: function () {
						map_highlight($(this).attr('class'));
					},
					mouseleave: function () {
						map_highlight('start');
					}
				});

				body.find('.counties_list ul li a').bind({
					mouseenter: function () {
						map_highlight($(this).parent().attr('id'));
					},
					mouseleave: function () {
						map_highlight('start');
					}
				});

				map_highlight('start');

			}
		});

		body.find('.county_picker *[href]').warnOnExit();

	};



	//	Vimeo Thinger
	$.prototype.vimeo = function (settings) {

        var config = {
            id: false,
			width: 300,
			height: 225
        };

        if (settings) {
            config = $.extend(config, settings);
        }

		this.each(function () {

			$(this).flash({
				params: {
					allowfullscreen: true,
					allowscriptaccess: 'always',
					wmode: 'transparent'
				},
				height: config.height,
				width: config.width,
				swf: 'http://vimeo.com/moogaloop.swf',
				flashvars: {
					clip_id: config.id,
					color: '09d551',
					fullscreen: 1,
					server: 'vimeo.com',
					show_byline: 1,
					show_portrait: 0,
					show_title: 1
				}
			});

		});

        return this;

	};



	$.prototype.prepThemeForm = function () {

		this.each(function () {

			if (body.find('input#colour').length) {
				$('<div id="colour_picker"></div>').insertBefore('input#colour');
				body.find('#colour_picker').farbtastic('input#colour');

				body.find('.bg_pos').bgPosPicker();
			}

		});

        return this;

	};



	$.prototype.themeRater = function () {

		this.each(function () {

			var form,
			    fieldset,
			    theme_id,
			    rating_el,
			    rating_val,
			    stars_html,
			    stars;

			form     = $(this);
			fieldset = form.find('fieldset');
			theme_id = fieldset.find('input[name=theme_id]').val();

			fieldset.find('button').remove();

			form.bind('submit', function (event) {

			    event.preventDefault();

			});

			rating_el  = fieldset.find('input:checked');
			rating_val = rating_el.val();

			stars_html = '<span class="cancel">0 Stars</span>';
			stars_html += '<span>1 Star</span>';
			stars_html += '<span>2 Stars</span>';
			stars_html += '<span>3 Stars</span>';
			stars_html += '<span>4 Stars</span>';
			stars_html += '<span>5 Stars</span>';

			//	Insert HTML
			$('<div />', {
			    html: stars_html
			}).appendTo(fieldset);

			stars = fieldset.find('span');

			body.find(stars[rating_val]).addClass('active').prevAll(':not(.cancel)').addClass('active');

			//	add classes to set initial styles

			stars.bind({
				mouseenter: function () {
					stars.removeClass('active current');
					$(this).prevAll().andSelf().addClass('active');
				},
				mouseleave: function () {
					stars.removeClass('active current');
					body.find(stars[rating_val]).addClass('current').prevAll().andSelf().addClass('active');
				},
				click: function () {

					var checked_star = $(this);

					rating_val = checked_star.index();

					if (rating_val > 0) {
						fieldset.find('label:eq(' + (rating_val - 1).toString() + ') input').trigger('click');
                    }

					stars.removeClass('active current');
					checked_star.addClass('current').prevAll().andSelf().addClass('active');

					$.when($.ajax({
						url: form.attr('action'),
						data: {
							ajax: true,
							rating: rating_val,
							theme_id: theme_id
						},
						dataType: 'json',
						type: 'POST'
					})).then(function (data) {
						var qTipStyle = data.status === 'win' ? 'green' : 'red';

						checked_star.buildAndTriggerQtip({
							titleContent: data.message,
							styleType: qTipStyle
						});
					});

				}
			});

			form.show();
		});

        return this;

	};



	$.prototype.registerWhat = function () {

		this.each(function () {

			var org_p     = $(this),
				org_label = org_p.find('label'),
				org_span  = org_p.find('span');

			org_span.css('display', 'none');

			$('<span class="reg_trigger">(<a href="#">' + text.what_is_this + '</a>)</span>').insertAfter(org_label);

			body.find('.reg_trigger a').bind('click', function () {
				org_span.toggle();
				return false;
			});

		});

        return this;

	};



	$.prototype.multiDates = function () {

		this.each(function () {

			var dates_section = $(this);

			$('<p class="add_another"><a href="#">Add another date?</a></p>').appendTo(dates_section);

			dates_section.find('.add_another a').bind('click', function () {
				var date_fields = dates_section.find('p.date_fields'),
					field_num   = date_fields.length.toString();

				dates_section.find('p.date_fields:first')
					.clone()
					.insertBefore('p.add_another')
					.find('option')
					.removeAttr('selected');

				date_fields.last()
					.find('select.select_year')
					.attr('name', 'dates_' + field_num + '-year')
					.end()
					.find('select.select_month')
					.attr('name', 'dates_' + field_num + '-month')
					.end()
					.find('select.select_day')
					.attr('name', 'dates_' + field_num + '-day')
					.end();

				return false;
			});
		});

        return this;

	};



	$.prototype.mediaPlayer = function () {

	    this.each(function () {
			var player = $(this),
				tabs   = player.find('ul.player_tabs li a'),
				panels = player.find('.player_content');

			panels.hide();

			tabs.bind('click', function (event) {
			    event.preventDefault();

				var clicked = $(this),
				    li      = clicked.parent(),
					show    = clicked.attr('rel');

                li.addClass('active').siblings().removeClass('active');

				body.find('.player_content').hide();
				body.find('#' + show, player).show();

			}).first().trigger('click');

			player.find('ul.slideshow').cycle();
		});

        return this;

	};

	//	Warn on Exit
	$.prototype.warnOnExit = function () {

		this.bind('click', function (event) {

		    event.preventDefault();

			var link       = $(this),
				target_url = link.attr('href'),
				qs         = 'lang=' + language + '&target_url=' + target_url;

			body.find('object').fadeOut(250);

			if (link.parent().hasClass('clic_yes')) {
				qs += '&clic_site=true';
			}

			link.colorbox({
				href:    '/incs/actions/warn_on_exit.php?' + qs,
				opacity: 0.5,
				open:    true,
				width:   300
			});

		});

        return this;

	};



    $.prototype.equalHeights = function (settings) {

        var config = {};

        if (settings) {
            $.extend(config, settings);
        }

        if (config.element) {
            this.each(function () {

                var elements   = $(this).find(config.element),
                    max_height = 0;
                
                elements.each(function () {

                    var element = $(this);

                    if (element.height() > max_height) {
                        max_height = element.height();
                    }

                });

                elements.height(max_height);

            });
        }

        return this;

    };



    /*	Make Rocket Go Now!
     */

    root.ready(function () {

        /*  Cache the godforsaken <html>, <head> & <body> elements, if you're
            in to that kind of thing...
         */

        html = root.find('html');
        head = html.find('head');
        body = html.find('body');



        /*  Any other variables we need to save?
         */

        language = html.attr('lang');
		text     = language === 'en' ? translations.en : translations.cym;



        /*  Fire off any functions that need to be fired, or just do what
            you like here... Set some variables, you know? It'll feel good...
         */



        /*  Invoke plugins, yo... Like this:
            body.find('#element').functionName({ ... });
         */

		body.find('.media_player').mediaPlayer();
		body.find('.dates_section').multiDates();
		body.find('#multi').multiImages();
		body.find('.like_this').likeCommentWithAjax();
		body.find('.report_abuse').reportAbuseWithAjax();
		body.find('.ajax_form').postWithAjax({ type: 'json' });
		body.find('input#colour').prepThemeForm();
		body.find('.orgs_checks').registerWhat();
		body.find('.star_rater').themeRater();

		if (!html.hasClass('ie6')) {
			$.clicmap();
		}



        /*  Other Bindings and whatever the hell
         */

        body.find('form#years_dropdown select').bind('change', function () {
			window.location = $(this).val();
		});

		body.delegate('a.colorbox_close', 'click', function () {
			$.prototype.colorbox.close();
			return false;
		});

		if (html.hasClass('ie')) {
			body.find('.info_index_cats li:nth-child(3n+1)').addClass('new_row');
		}

    });



    /*  Function's gotta return SOMETHING, right?
     */

    return null;

}(jQuery, this, this.document));

