$(document).ready(function () {
    //remove no JS info bar
    $('.disabledJS').remove();

    searchActive();
    servicesDropdown();
    caseStudyDropdown();
    heroCarousel();
    aboutSlider();
    accordian();
    backToTop();
    quicklinks();
    //contact us page
    locationsTabs();
    //for the client case study image links appearing at the bottom of some of the pages
    imgCrossFade();

    $('#clientList').show();
    $('#workClientList').show();
    $('#clientList .clientsDropDown ul').easyListSplitter({ colNumber: 4 });
    $('#workClientList .workClientListDropdown ul').easyListSplitter({ colNumber: 4 });
    $('.clientlisting ul').easyListSplitter({ colNumber: 3 });
    $('#workListing ul li:nth-child(4n)').addClass('last');
    //$('#latestWork ul li:nth-child(4n)').addClass('last');
    $('.project').addClass('bdrTop');
	$('.project:first').removeClass('bdrTop');
    //$('.project .content img:last-child').css('margin-bottom', '10px');
	$('#topNav li:first').addClass('noBdr');

    //extending validation as default values are invalid data
    $.validator.addMethod('requiredDefault', function (value, element, param) {
        return value && value != param;
    }, 'This field is required.');

    //contact us page
    $('.location .w710 img').hide();

    contactUsValidation();
    subscribeValidation();
    careersTabs(); //used in careers page
    ourPeople();

    //replace dropdowns in news page
    replacedropdowns("newsservice");
    replacedropdowns("newstype");

    clientfilter(); //used in filtering our work

    dropdowns(); //add events to custom dropdowns

    //awards page
    initAwardsList();

    //add paging to news page
    addPaging('newslist', 10);
    //add paging to 'Our Thinking' articles
    //addPaging('thoughtssearchlist', 5);

});

function servicesDropdown() {
	var servicesHolder = $('.servicesDropDown, .clientsDropDown');
	var heading = $('#ourServices h2, #clientList h2')
	
	if ($('body').hasClass('home')) {
		servicesHolder.hide();
	} else {
		servicesHolder.show();
	}
	
	heading.bind({
		click: function() {
			servicesHolder.slideToggle('fast');
			$(this).toggleClass('open')
		},
		mouseenter: function() { $(this).css('cursor', 'pointer'); },
		mouseleave: function() { $(this).css('cursor', 'auto'); }
	});
}

function caseStudyDropdown() {
	var clientsHolder = $('.workClientListDropdown');
	var heading = $('#workClientList h2')
	
	clientsHolder.hide();

	heading.bind({
		click: function() {
			clientsHolder.slideToggle('fast');
			$(this).toggleClass('open')
		},
		mouseenter: function() { $(this).css('cursor', 'pointer'); },
		mouseleave: function() { $(this).css('cursor', 'auto'); }
    });

    //close filter
    $('#clientList h2').click();
    $('.clientsDropDown').hide();
}

function searchActive() {
    var searchBox = $('#search, #emailBox, input#name, input#email, .searchnews input.textbox, #data');

	searchBox.addClass('idleField');
	searchBox.focus(function() {
		$(this).removeClass('idleField').addClass('focusField');
		if (this.value == this.defaultValue){ 
			this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	searchBox.blur(function() {
		$(this).removeClass('focusField').addClass('idleField');
		if ($.trim(this.value) == ''){
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
}

var t; //timer for the carousel

function heroCarousel() {
	
	// Add the slide numbers
	var slideNumber = $('#heroCarousel .slides_container .slideCount p');
	for(var index = 0; index < slideNumber.length; index++){
		slideNumber.eq(index).prepend(index+1);
	}
	
    //set timer
    t = setTimeout("shownextslide()", 5000);
	
	// Next/Prev buttons
	$('#heroCarousel a.prev').live('click', function() {
		clearTimeout(t);
		if ($(this).closest('.active').prev().html() == null) {
			nextslide = $('.slides_container .slide:last');
		}
		else var nextslide = $('#'+$(this).closest('.active').prev().attr('id'));
        showslide(nextslide);
		return false;
	});
	
	$('#heroCarousel a.next').live('click', function() {
		clearTimeout(t);
		if ($(this).closest('.active').next().html() == null) {
			nextslide = $('.slides_container .slide:first');
		}
		else var nextslide = $('#'+$(this).closest('.active').next().attr('id'));
        showslide(nextslide);
        return false;
	});
	
	$('#heroCarousel #slide1 .info').css('right', '0');
	
    //add events to pager
    $('#heroCarousel ul.pagination li a').live('click', function () {
        clearTimeout(t);
        var nextslide = $($(this).attr('href'));
        showslide(nextslide);
        return false;
    });
}

function showslide(nextslide) {
    //show next slide as hidden
    $('.slides_container .active').css("z-index", "100");
    nextslide.css("z-index", "10");
    $('.slides_container .slide .info').css("right", "-225px"); //nextslide.children('.info').css("bottom", "-445px");
    nextslide.show();
    nextslide.css("opacity", "1");
	
    //cross fade into next slide
    $('.slides_container .active').animate({ opacity: 0 }, 400, function () {
        $('.slides_container .active').hide();
        //paging
        $('#heroCarousel ul.pagination li').removeClass('current');
        $('#heroCarousel ul.pagination li a[href="#' + nextslide.attr('id') + '"]').parents('li').addClass('current');
        //slide up the info box
        nextslide.children('.info').animate({ right: 0 }, 600, function () {
            //set classes for next iteration
            nextslide.addClass('newactive');
            $('.slides_container .active').removeClass('active');
            $('.slides_container .newactive').removeClass('newactive').addClass('active');
            t = setTimeout("shownextslide()", 5000);
        });
    });
}

function shownextslide() {
    //get the last slide
    var nextslide = null;
    if ($('.slides_container .active').next().html() == null) {
        nextslide = $('.slides_container .slide:first');
    }
    else nextslide = $('.slides_container .active').next();

    showslide(nextslide);
}

function aboutSlider() {
	$('#slides').slides({
		generatePagination: false,
		play: 5000,
		pause: 2500,
		slideSpeed: 650
	});
}

function projectSlider() {
	$('#projectSlides').slides({
		generatePagination: false,
		generateNextPrev: true,
		play: 5000,
		pause: 2500,
		slideSpeed: 650,
		preload: true
	});
}

function accordian() {
	var accordHeading = $('.accordian h2');
	var accordDiv = $('.accordian .slide');

	accordDiv.hide();
	//accordHeading.first().addClass('accordActive');
	//accordDiv.first().show();
	
	accordHeading.bind({
		click: function() {
			$(this).next().slideToggle('fast');
			$(this).toggleClass('accordActive')
		},
		mouseenter: function() { $(this).css('cursor', 'pointer'); },
		mouseleave: function() { $(this).css('cursor', 'auto'); }
	});
}

function backToTop() {
    $('.expertise-item a.top').live('click', function () { $('html, body').animate({ scrollTop: 0 }, 'slow'); return false; });
	$('a.backToTop').click(function() {
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		return false;
	});
}

function stickyIntro() {
	/*
	if ($('#stickyInfo').length) {
		$(window).scroll(
			function() {
				var menu = $('#stickyInfo');
				var menuPos = menu.position();
				if (($(window).scrollTop() > menuPos.top)) { 
					menu.addClass('sticky'); 
					$('#introSection').removeClass('noBdr'); 
				} else if (($(window).scrollTop() < 179)) { 
					menu.removeClass('sticky'); 
					$('#introSection').addClass('noBdr'); 
				}
			}
		);
	}
*/
}

function quicklinks() {
    $('.quicklinks li a').click(function () {
        var full_url = this.href;
        var parts = full_url.split('#');
        var trgt = parts[1];
        var target_offset = $('#' + trgt).offset();
        if (target_offset != null) {
            var target_top = target_offset.top;

            $('html, body').animate({ scrollTop: target_top - 200 }, 'slow');
        }
        return false;
    });
}

function locationsTabs() {
	$('.location').hide();
	$('.location:first').show();
	$('ul.locationNav li:first').addClass('active');

    //not used - page needs to be reloaded for the maps to work
    /*$('ul.locationNav a').click(function () {
        var tab = $(this).attr('href');
		console.log(tab);
        $('ul.locationNav li').removeClass('active');
        $(this).parent().addClass('active');
        $('.location').hide();
        $(tab).fadeIn('fast');
        return false;
    });*/

    //check the URL for querystrings to open page directly to specified location tab
    //pass in /contact/?office=dubai or /contact/?office=paris
    var url = document.URL;
    if (url.indexOf('?office=', 0) >= 0)
    {
        var office = url.substring(url.indexOf('?office=', 0) + 8, url.length);
        //$('ul.locationNav a[href=#' + office + ']').click();
        var tab = '#' + office;
        $('ul.locationNav li').removeClass('active');
        $('ul.locationNav a[href="?office=' + office + '"]').parents('li').addClass('active');
        $('.location').hide();
        $(tab).fadeIn('fast');
        return false;
    }
}

function imgCrossFade() {
	$('a.crossfade').hover(
		function () {
			$(this).find('img.on').show();
			$(this).find('img.off').animate({ opacity: 0 }, 350);
		}, 
		function () {
			$(this).find('img.off').animate({ opacity: 1 }, 350);
		}
	);
}

function contactUsValidation() {

    if ($("#contactform").html() != null) {

        $("#contactform input, #contactform textarea").focus(function () {
            if ($(this).val() == $(this).attr('defaultValue')) $(this).val('');
        });
        $("#contactform input, #contactform textarea").blur(function () {
            if ($(this).val() == '') $(this).val($(this).attr('defaultValue'));
        });

        //perform validation
        $("#contactform").validate({
            rules: {
                name: { requiredDefault: 'Name' },
                email: { requiredDefault: 'Email' },
                feedback: { requiredDefault: 'Message' }
            }
        });

    } //if

}

function subscribeValidation() {
    $("#subscribe").validate({
        rules: {
            emailBox: { requiredDefault: 'Enter email' }
        },
        errorPlacement: function (error, element) {
            error.insertAfter('#emailButton');
        }
    });
}

function careersTabs() {
    //all information are displayed by default when there is no JS

    //setup active city on subnav
    $('.careers-page #subNav li').removeClass('active');
    $('.careers-page #subNav li:eq(1)').addClass('active');
    //show details for first city
    $('.careers-city').hide();
    $('.careers-city:first').show();

    //click event
    $('.careers-page #subNav li a').live('click', function () {
        $('.careers-page #subNav li').removeClass('active');
        $(this).parents('li').addClass('active');
        $('.careers-city').hide();

        $($(this).attr('href')).show();
        return false;
    });
}

function ourPeople() {
    /*$('#ourPeople li:nth-child(6n)').addClass('lastCol');
    $('#ourPeople li:nth-child(6n+1)').addClass('colA');
    $('#ourPeople li:nth-child(6n+2)').addClass('colA');
    $('#ourPeople li:nth-child(6n+3)').addClass('colB');
    $('#ourPeople li:nth-child(6n+4)').addClass('colB');
    $('#ourPeople li:nth-child(6n+5)').addClass('colC');
    $('#ourPeople li:nth-child(6n)').addClass('colC');*/
    /*modified to work in google chrome:
    $('#ourPeople li:nth-child(6n+1), #ourPeople li:nth-child(6n+2)').addClass('colA');
    $('#ourPeople li:nth-child(6n+3), #ourPeople li:nth-child(6n+4)').addClass('colB');
    $('#ourPeople li:nth-child(6n+5), #ourPeople li:nth-child(6n)').addClass('colC');*/

	var peopleConfig = {
		 interval: 100,
		 sensitivity: 4,
		 over: showPanel,
		 timeout: 100,
		 out: hidePanel
	};
	
	$('#ourPeople li').hoverIntent(peopleConfig);
	
	function showPanel() {
		var panelPos =  $(this).position();
		//$('#ourPeople li').not(this).fadeTo('fast', '0.5');
		/*
		if ($(this).hasClass('colA')) {
			$(this).find('.caption').css('top', panelPos.top-100).css('left', panelPos.left+55).fadeTo('fast', '1.0');
		}
        if ($(this).hasClass('colB')) {
		    $(this).find('.caption').css('top', panelPos.top - 100).css('left', panelPos.left - 175).fadeTo('fast', '1.0');
		}
		if ($(this).hasClass('colC')) {
		    $(this).find('.caption').css('top', panelPos.top - 100).css('left', panelPos.left - 175).fadeTo('fast', '1.0');
		}*/
		$(this).find('.caption').css('top', panelPos.top+40).css('left', panelPos.left+10).fadeTo('fast', '1.0');
	}
	
	function hidePanel() {
		$(this).find('.caption').fadeOut('fast');
		//$('#ourPeople li').fadeTo('fast', '1.0');
	}
}

function clientfilter() {
    $('.clientfilter a.filter_off').live('click', function () {

        //selects the filter tick box
        $('.clientfilter a.filter_on').removeClass('filter_on').addClass('filter_off');
        $(this).removeClass('filter_off').addClass('filter_on');

        //add opacity to non-selected items, remove opacity to selected items
        $('#workListing li').removeClass('activefilter');
        $('#workListing li').each(function (i) {
            var selected = $('.clientfilter a.filter_on').attr('href').substring(1);
            //alert($(this).attr('class'));
            if (selected == 'all' || $(this).hasClass(selected)) {
                $(this).css('opacity', '1');
                $(this).addClass('activefilter');
            }
            else {
                $(this).css('opacity', '0.2');
            }
        });

        //scroll down to first row
        if (url.indexOf('?filter=', 0) >= 0) {
            $('html, body').animate({ scrollTop: $('#workListing li.activefilter:first').position().top + 210 }, 'slow');
        }
        else $('html, body').animate({ scrollTop: $('#workListing li.activefilter:first').position().top + 290 }, 'slow');

        return false;
    });
    $('.clientfilter a.filter_on').live('click', function () {
        return false;
    });


    //are we adding filtering via URL
    var url = document.URL;
    if (url.indexOf('?filter=', 0) >= 0) {
        var filter = url.substring(url.indexOf('?filter=', 0) + 8, url.length);
        $('.clientfilter a[href="#' + filter + '"]').click();
    }
}

//currently only used in our thinking>topics and news
function dropdowns() {
    $('a.dropdown').next('ul.dropdown').hide();
    $('a.dropdown').live('click', function () {
        if ($(this).next('ul.dropdown').is(':visible')) $(this).next('ul.dropdown').hide();
        else $(this).next('ul.dropdown').show();
        //if ($(this).next('ul.dropdown').attr('id') == 'topics' || ) $(this).html('Service');
        return false;
    });

    //are we doing a search via tags? if so, pre-select the services dropdown
    /*var url = document.URL;
    if (url.indexOf('?cat=tag&data=', 0) >= 0) {
        var filter = url.substring(url.indexOf('?cat=tag&data=', 0) + 14, url.length);
    }*/
}

//pass in the class name of the select element to replace with a UL LI
function replacedropdowns(selectClass) {
    var ulhtml = "";
    $('select.' + selectClass + ' option').each(function (i) {
        if (i == 0) ulhtml = '<a class="dropdown" href="#">' + $(this).html() + '</a> <ul id="' + $(this).html() + '" class="dropdown">';
        else {
            ulhtml += '<li><a href="?cat=tag&data=' + $(this).val() + '">' + $(this).html() + '</a></li>';
        }
    });
    ulhtml += '</ul>';
    $('select.' + selectClass).after(ulhtml);
    $('select.' + selectClass).hide();
}


function initAwardsList() {

    //hide contents
    $('ul.awardslist li .award-content p').hide();
    $('ul.awardslist li .award-content').each(function () {
        $(this).children('p:first').show();
        if ($(this).children('p').length > 1) {
            $('ul.awardslist li .link-area').hide();
            $(this).append('<p class="readmore"><a href="#">Read more</a></p>');
        }
    });

    //read more
    $('ul.awardslist li .award-content p.readmore').live('click', function () {
        $(this).parents('.award-content').children('p').show();
        $(this).children('a').html('Read less');
        $(this).parents('.award-content').siblings('.award-image').children('.link-area').show();
        $(this).removeClass('readmore').addClass('readless');
        return false;
    });

    //read less
    $('ul.awardslist li .award-content p.readless').live('click', function () {
        $(this).parents('.award-content').children('p').hide();
        $(this).parents('.award-content').children('p:first').show();
        $(this).parents('.award-content').children('p.readless').show();
        $(this).parents('.award-content').siblings('.award-image').children('.link-area').hide();
        $(this).children('a').html('Read more');
        $(this).removeClass('readless').addClass('readmore');
        return false;
    })

    addPaging('awardslist', 5);
}

/*
adds a paging to a UL list 
works only on 1 instance per page - do not add paging to more than 1 list on a page
Pass in :   ulClass is the UL's class
            itemsPerPage is the number of items to show per page
used in :   About Us > Awards
*/
function addPaging(ulClass, itemsPerPage) {
    if ($('.' + ulClass + ' li').length > itemsPerPage) {
        //then we add paging
        var itemscount = $('.' + ulClass + ' li').length;
        $('.' + ulClass).after(function () {
            var baseelem = '<div class="pages-section"> <div class="pages-columns">';
            baseelem += '<ul>';
            for (var i = 1; i <= Math.ceil(itemscount / itemsPerPage); i++) {
                if (i == 1)
                    baseelem += '<li><a href="' + replaceQueryString(document.URL, 'pg', i) + '" class="active" id="page-' + i + '">' + i + '</a></li>';
                else
                    baseelem += '<li><a href="' + replaceQueryString(document.URL, 'pg', i)  + '" id="page-' + i + '">' + i + '</a></li>';
            }
            baseelem += '</ul><a href="#" class="prevpage">Previous page</a></div><a href="' + replaceQueryString(document.URL, 'pg', '2') +'" class="nextpage">Next page</a></div>';
            return baseelem;
        });
        //show only first page
        $('.' + ulClass + ' li:gt(' + (itemsPerPage - 1) + ')').hide();
        //then add paging click events
        $('.pages-section a.prevpage').live('click', function () {
            if ($(this).attr('href') == '#') return false;
        });
        $('.pages-section a.nextpage').live('click', function () {
            if ($(this).attr('href') == '#') return false;
        });
    }

    var checkurl = document.URL;
    if (checkurl.indexOf('?pg=', 0) > 0 || checkurl.indexOf('&pg=', 0) > 0) {
        //is this a valid page number
        var pagenumber = checkurl.substring(checkurl.indexOf('pg=', 0) + 3, checkurl.length);
        if (!Number(pagenumber)) pagenumber = 1; //if we're passed an invalid page number, display page 1
        pagenumber = parseInt(pagenumber);
        var itemscount = $('.' + ulClass + ' li').length;
        var numpages = Math.ceil(itemscount / itemsPerPage);
        if (parseInt(pagenumber) > numpages) pagenumber = numpages; //if we're passed a page number > allowed number of pages, pass in the last page
        //show page
        $('.' + ulClass + ' li').show();
        $('.' + ulClass + ' li:lt(' + ((pagenumber - 1) * itemsPerPage) + ')').hide();
        $('.' + ulClass + ' li:gt(' + ((pagenumber * itemsPerPage) - 1) + ')').hide();
        $('.pages-section ul li a').removeClass('active');
        $('#page-' + pagenumber).addClass('active');
        //change previous page and next page links
        if (pagenumber > 1) $('.pages-section a.prevpage').attr('href', replaceQueryString(document.URL,'pg',pagenumber - 1));
        else $('.pages-section a.prevpage').attr('href', '#');
        if (pagenumber < numpages) $('.pages-section a.nextpage').attr('href', replaceQueryString(document.URL, 'pg', pagenumber + 1));
        else $('.pages-section a.nextpage').attr('href', '#');
    }
} //addPaging()

function replaceQueryString(url, param, value) {
    if (url.indexOf('?',0) < 0) return url +='?' +param + '=' + value;
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else
        return url + '&' + param + "=" + value;
} //replaceQueryString
