// -------------------------------------------------------------------
// 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') {




    // ------------------------------
    // 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');
            }
        }
    };
    
    // Show / hide for JBE frequency form selects
    function showHideFrequencyControls(selectbox) {
        if (selectbox.val() == 1) {
            $('#jbeDaily').slideDown('fast');
        } else {
            $('#jbeDaily').slideUp('fast');
        }
    }

    // ------------------------------
    // 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");
        }
        
        (function() {
        	if (typeof jQuery.fn.colorbox !== "undefined") {
        		$(".colorbox").colorbox({ width: "650px", height: "80%", iframe: true });
        	}
        })()

        // 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();

        // 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);

            }
        })



            // 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="clear">Clear</a></span>');

                    // add the All / Clear switchers
                    $(this).find('.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;
                    });
                };

            });

        // if IE6 don't implement collapsable menu item
        if(jQuery.browser.msie && jQuery.browser.version == '6.0'){
			return;
		}else{
            $("#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');
                    });
                }
            }

        }


		// Pull placeholder from input's that have one and use it as example inputs (for browsers that don't support HTML5).
		$('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');
        // 	};
        // });

        // Show / hide for JBE frequency form selects
        showHideFrequencyControls($('select#Frequency'));
        $('select#Frequency').change(function() {
            var selectbox = $(this);
            showHideFrequencyControls(selectbox);
        });


        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

    });


	
	// JDW - adapted from Nick Sky's code for clearing the radial town input on a location change
	$(document).ready(function(){
		var $rcc = $('#RadialCountryCode'),
			$rt = $('#RadialTown');
		
		if($rcc.length && $rt.length){
			$rcc.bind('change', function(){
				$rt.val('');
			});
		}
	});


}; // END


