// -------------------------------------------------------------------
// Madgex Limited
// Copyright (c) 2008 Madgex Limited. All Rights Reserved.
// Common, version 1.1 (jQuery version)
// James Wragg
// -------------------------------------------------------------------


// Only continue if jQuery has been loaded
if (typeof jQuery != 'undefined') {


    // Clears the value of the hidden country code field on the radial search
    // when a user changes the value of the town/postcode input field.
    function clearRadialCountryCode() {
        var countryCodeField = $('#RadialCountryCode');
        countryCodeField.val('');
    }

    // ------------------------------
    // Utility functions used accross the site
    // ------------------------------
    function paginationAjaxify() {
        $('#resultsTarget div.paginationajax a').each(function() {

            if ($(this).hasClass('page') || ($(this).hasClass('prevPageSet') || $(this).hasClass('nextPageSet'))) {
                $(this).click(function() {
                    // var hash = $(this).text();
                    // var hash = /(\d+)(\/)?/.exec(this.href)[1];

                    var hash = "", reqUrl = "";

                    // get the base URL of the link clicked, and remove the querystring
                    if (this.href.indexOf('?') != "-1") {
                        reqUrl = this.href.split('?')[0];
                    } else {
                        reqUrl = this.href;
                    }

                    // extract the page number from the rel attribute of this link (e.g. rel="pageNo:5")
                    var relArr = jQuery.trim($(this).attr('rel')).split(' ');
                    $.each(relArr, function(i) {
                        if (relArr[i].indexOf('pageNo') != '-1') {
                            hash = relArr[i].split(':')[1];
                        }
                    });

                    // add trailing slash if not present
                    if (reqUrl.substring(reqUrl.length - 1, reqUrl.length) != "/") {
                        reqUrl = reqUrl + '/';
                    }

                    // if the end of the url has the page number, strip it off - it's added automatically later.
                    var urlArr = reqUrl.split('/');
                    if (urlArr[urlArr.length - 2] == hash) {
                        reqUrl = reqUrl.substring(0, reqUrl.indexOf('/' + hash) + 1);
                    }

                    $.historyLoad(hash, reqUrl);
                    return false;
                });
            } else {
                $(this).click(function() {
                    fetchPage(this.href);
                    return false;
                });
            }

        });
    }

    function fetchPage(url, n) {

        if (n) {
            url = url + n + '/';
        }

        $('#resultsTarget').prepend('<div id="results-overlay">&nbsp;</div>');
        var overlay = $('#results-overlay');

        $.ajax({
            type: "GET",
            url: url,
            success: function(data) {
                $('#resultsTarget .resultsTarget-content').html(data);
                overlay.fadeOut('fast', function() {
                    $(this).remove();
                });
                paginationAjaxify();
            },
            error: function(data) {
                alert('There was a problem fetching the page requested. Please refresh this page and try again.');
            },
            timeout: function(data) {
                alert('There was a problem fetching the page requested. Please refresh this page and try again.');
            }
        });

    }

    function pageload(hash, obj) {

        var url = './', isInitPageLoad = false;

        if (typeof obj == 'object') {
            if (obj.url) {
                url = obj.url;
            }
            if (obj.isInitPageLoad) {
                isInitPageLoad = true;
            }
        }

        // hash doesn't contain the first # character.
        if (hash) {
            // restore ajax loaded state
            fetchPage(url, hash);
        } else if (!isInitPageLoad) {
            // fetch the first page if you click the browser back button to a non-hashed url, not when
            // arriving at the page without a page hash.
            fetchPage(url, 1);
        }

    }


    jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
        return this.animate({ opacity: 'toggle', height: 'toggle' }, speed, easing, callback);
    };

    jQuery.fn.fadeToggle = function(speed, easing, callback) {
        return this.animate({ opacity: 'toggle' }, speed, easing, callback);
    };


    var twisterStates = {
        // read the twisters saved state & set.
        set: function() {
            var states = $.cookie('twisterStates');
            if (states) {
                var statesArr = decodeURIComponent(states).split(',');
                $("#secondary h3.collapsable").each(function(i) {

                    // get the H3 text value (without any additional gumpf - 'All | Clear' etc.)
                    var text = $(this).get(0).firstChild.nodeValue;

                    if ($.inArray(text, statesArr) != '-1') {
                        var target = $(this).find("+ *");
                        var allClear = $(this).find("> span.allClear");

                        target.hide();
                        allClear.hide();
                        target.prev().toggleClass("collapsed");
                    };

                });
            }
        },
        // read the current user set twister states & save in cookie
        save: function() {
            var statesArr = [], title = "";
            $("#secondary h3.collapsable").each(function(i) {

                if ($(this).hasClass('collapsed')) {
                    title = this.firstChild.nodeValue;
                    if (title.indexOf('<span') != "-1") {
                        title = title.substring(0, title.indexOf('<span'));
                    }
                    statesArr.push(title);
                };

            });
            var cookieFormat = encodeURIComponent(statesArr.join(','));
            $.cookie('twisterStates', cookieFormat);
        }
    };


    var checkRow = {
        add: function(elem, opt) {
            $(elem).parent().addClass('checked-row');
            var resultsDiv = $(elem).parents('div.check-scroller').next();
            var label = $(elem).next().text().replace(/ /g, '&nbsp;');
            resultsDiv.append('<div id="option-' + elem.id + '" class="selection-item">' + label + '</div>');

            if ($(elem).parents('fieldset').find('input:checked').length > 0) {
                checkRow.toggleTitle($(elem).parents('div.check-scroller').next(), 'show');
            }
        },
        remove: function(elem) {
            $('#' + elem.id).parent().removeClass('checked-row');
            $('#option-' + elem.id).remove();

            // if last item, hide the 'your selection' title
            if ($(elem).parents('fieldset').find('input:checked').length == 0) {
                checkRow.toggleTitle($(elem).parents('div.check-scroller').next(), 'hide');
            }
        },
        toggleTitle: function(resultsDiv, action) {
            var titleElem = $(resultsDiv).find('div.title');

            if (action == 'show') {
                titleElem.slideDown('fast', 'easeOutExpo');
            } else {
                titleElem.slideUp('fast', 'easeOutExpo');
            }
        }
    };


    // ------------------------------
    // When the DOM's ready for scripting, let's go
    // ------------------------------
    $(document).ready(function() {

        // JS & jQuery is available and running - add js class to body for extra CSS specificity 
        function bodyJS() {
            $('body').addClass("js");
        }


        // add the auto-expanding functionality to textareas
        /*
        $('textarea.expanding').autogrow({
        maxHeight: 100,
        minHeight: 80,
        lineHeight: 18
        });
        */

        // tweak checkbox positions for IE<8 
        // if($.browser.msie && $.browser.version < 8 ){
        // 	$('input.checkbox').css({position: 'static', marginTop: '0', marginRight: '0'});
        // }


        // show the selections under the check-scroller on page load & on check.
        // create selections container
        $('form div.formWrapper div.check-scroller').parent()
			.append('<div class="checkbox-selection"><div class="title">Your selection:</div></div>')
			.parent()
			.find('div.title')
			.hide();

        // Disable accidental selection of text in check-scrollers
        // Causing a JS error, knocking out the tabs on the homepage
        //$('h3.collapsable, div.checkbox, div.check-scroller').disableTextSelect();

        // Read current selections & show labels
        $('form div.formWrapper div.check-scroller').each(function() {
            var checkedBoxes = $(this).find('input:checked');
            if (checkedBoxes.length > 0) {
                //console.log(checkedBoxes.get(0));
                $.each(checkedBoxes, function() {
                    checkRow.add(this);
                });
            }
        })

        // add selection feedback when options are toggled
        $('form div.formWrapper div.check-scroller input[type=checkbox]').click(function() {
            // TODO: add hierarchical selections
            if (this.checked) {
                checkRow.add(this, 'slideIn');
            } else {
                checkRow.remove(this);

            }
        })


        // if IE6 don't implement collapsable menu item
        if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
			return;
		}else{

            // Every h3 header that has the 'collapsable' class; add the collapse/expand event to the next element
            $("#secondary h3.collapsable").each(function() {
                var nextElem = $(this).next();

                if (nextElem.hasClass('collapse-target') && nextElem.children(".check-scroller").length) {
                    $(this).append('<span class="allClear"><a href="#" class="all">All</a><span class="pipe"> | </span><a href="#" class="clear">Clear</a></span>');

                    // add the All / Clear switchers
                    $(this).find('.all, .clear').click(function(e) {
                        var option = $(this).text();
                        var checksWrapper = $(this).parents('h3').next();

                        switch (option) {
                            case "All":
                                $(checksWrapper).find('input[type=checkbox]').each(function() {
                                    $(this).get(0).checked = true;
                                })
                                break;
                            case "Clear":
                                $(checksWrapper).find('input[type=checkbox]').each(function() {
                                    $(this).get(0).checked = false;
                                })
                                break;
                        }

                        e.stopPropagation();
                        return false;
                    });
                };

            });

            $("#secondary h3.collapsable")
				.css({ cursor: "pointer" })
				.click(function() {
				    var target = $(this).next();
				    $(this).find('span.allClear').fadeToggle();

				    target.slideFadeToggle('slow', 'easeOutExpo');
				    target.prev().toggleClass('collapsed');
				    twisterStates.save();
				});


            function addHoversForIE6() {
                // Add hover action to facet headers & checkbox rows in IE6 - as IE6 doesn't support :hover on non-hyperlinks
                if ($.browser.msie && $.browser.version < 7) {

                    $('body#lister #secondary h3.collapsable').hover(function() {
                        $(this).addClass('hover');
                    }, function() {
                        $(this).removeClass('hover');
                    });

                    $('div.check-scroller div.checkbox').hover(function() {
                        $(this).addClass('checkbox-hover');
                    }, function() {
                        $(this).removeClass('checkbox-hover');
                    });
                }
            }
        }
        (function() {
            // Add date to header for Drapers jobs
            var d = new Date();
            var curr_date = d.getDate().toString();
            var lastPos = curr_date.length - 1;
            var dateUnit = curr_date.charAt(lastPos);
            var dateSuffix = "th";
            var month_name = "January"; 
            switch (d.getDate()) {
            	case 1:
            	case 21:
            	case 31:
            		dateSuffix = 'st'
            		break
            	case 2:
            	case 22:
            		dateSuffix = 'nd'
            		break
            	case 3:
            	case 23:
            		dateSuffix = 'rd'
            		break
            	default: dateSuffix = 'th'
            }
            var curr_month = d.getMonth();
            curr_month++;
            switch (curr_month) {
                case 1: month_name = "January";
                    break
                case 2: month_name = "February";
                    break
                case 3: month_name = "March";
                    break
                case 4: month_name = "April";
                    break
                case 5: month_name = "May";
                    break
                case 6: month_name = "June";
                    break
                case 7: month_name = "July";
                    break
                case 8: month_name = "August";
                    break
                case 9: month_name = "September";
                    break
                case 10: month_name = "October";
                    break
                case 11: month_name = "November";
                    break
                case 12: month_name = "December";
                    break
            };
            var curr_year = d.getFullYear();
            var headingDate = (curr_date + dateSuffix + " " + month_name + " " + curr_year);

            $('#header .wrapper').append('<p id="date">' + headingDate + '</p>');
        })();

        // Pull title from input's that have one and use it as example inputs.
        $('input, textarea').placeholder();
        // segregate indented lists in checkbox lists
        // $('div.locations fieldset.checkboxes label.indent0').each(function(i){
        // 	var node = $(this).parent().next().get();
        // 	if ( $(node).children('label.indent1, label.indent2').length > 0 && i != 0 ){
        // 		$(this).parent().addClass('divide');
        // 	};
        // });
        bodyJS(); 					// add body classes for css overrides

        if ($('#resultsTarget div.paginationajax').get(0)) {
            $.historyInit(pageload); // Load page state if set (AJAX history)
            paginationAjaxify(); 	// attach ajax pagination
        }

        twisterStates.set(); 		// restore saved twister states
        addHoversForIE6(); 		// IE6 doesn't normally offer hover on anything other than A tags

        // Tabs by Jack
        $('#tabs div').hide();
		$('#tabs .tabLinks:nth-child(3)').show();
		$('#tabs .menu').addClass('activated').find('li:nth-child(2)').addClass('active');
        $('#tabs .menu a').click(function() {
            $('#tabs .menu li').removeClass('active');
            $(this).parent().addClass('active');
            $('#tabs').children('div').hide().parent().find($(this).attr('href')).show();
            $(this).parent().parent().find('a').removeClass('active');
            $(this).addClass('active');
            return false;
        });

    });

}; // END
