//jQuey
var J = jQuery.noConflict();

J(document).ready(function ($) {
	
	//News Slideshow
	if (J('#news-rotator').length){
		J('#news-rotator').cycle({
			fx:			  'fade', // name of transition effect (or comma separated names, ex: fade,scrollUp,shuffle)
			timeout:	   4000,  // milliseconds between slide transitions (0 to disable auto advance)
			timeoutFn:     null,  // callback for determining per-slide timeout value:  function(currSlideElement, nextSlideElement, options, forwardFlag)
			continuous:	   0,	  // true to start next transition immediately after current one completes
			speed:		   1000,  // speed of the transition (any valid fx speed value)
			speedIn:	   null,  // speed of the 'in' transition
			speedOut:	   null,  // speed of the 'out' transition
			next:		   null,  // selector for element to use as click trigger for next slide
			prev:		   null,  // selector for element to use as click trigger for previous slide
			prevNextClick: null,  // callback fn for prev/next clicks:	function(isNext, zeroBasedSlideIndex, slideElement)
			prevNextEvent:'click',// event which drives the manual transition to the previous or next slide
			pager:		   null,  // selector for element to use as pager container
			pagerClick:	   null,  // callback fn for pager clicks:	function(zeroBasedSlideIndex, slideElement)
			pagerEvent:	  'click', // name of event which drives the pager navigation
			pagerAnchorBuilder: null, // callback fn for building anchor links:  function(index, DOMelement)
			before:		   null,  // transition callback (scope set to element to be shown):	 function(currSlideElement, nextSlideElement, options, forwardFlag)
			after:		   null,  // transition callback (scope set to element that was shown):  function(currSlideElement, nextSlideElement, options, forwardFlag)
			end:		   null,  // callback invoked when the slideshow terminates (use with autostop or nowrap options): function(options)
			easing:		   null,  // easing method for both in and out transitions
			easeIn:		   null,  // easing for "in" transition
			easeOut:	   null,  // easing for "out" transition
			shuffle:	   null,  // coords for shuffle animation, ex: { top:15, left: 200 }
			animIn:		   null,  // properties that define how the slide animates in
			animOut:	   null,  // properties that define how the slide animates out
			cssBefore:	   null,  // properties that define the initial state of the slide before transitioning in
			cssAfter:	   null,  // properties that defined the state of the slide after transitioning out
			fxFn:		   null,  // function used to control the transition: function(currSlideElement, nextSlideElement, options, afterCalback, forwardFlag)
			height:		  'auto', // container height
			startingSlide: 0,	  // zero-based index of the first slide to be displayed
			sync:		   1,	  // true if in/out transitions should occur simultaneously
			random:		   0,	  // true for random, false for sequence (not applicable to shuffle fx)
			fit:		   0,	  // force slides to fit container
			containerResize: 1,	  // resize container to fit largest slide
			pause:		   0,	  // true to enable "pause on hover"
			pauseOnPagerHover: 0, // true to pause when hovering over pager link
			autostop:	   0,	  // true to end slideshow after X transitions (where X == slide count)
			autostopCount: 0,	  // number of transitions (optionally used with autostop to define X)
			delay:		   0,	  // additional delay (in ms) for first transition (hint: can be negative)
			slideExpr:	   null,  // expression for selecting slides (if something other than all children is required)
			cleartype:	   !$.support.opacity,  // true if clearType corrections should be applied (for IE)
			cleartypeNoBg: true, // set to true to disable extra cleartype fixing (leave false to force background color setting on slides)
			nowrap:		   0,	  // true to prevent slideshow from wrapping
			fastOnEvent:   0,	  // force fast transitions when triggered manually (via pager or prev/next); value == time in ms
			randomizeEffects: 1,  // valid when multiple effects are used; true to make the effect sequence random
			rev:		   0,	 // causes animations to transition in reverse
			manualTrump:   true,  // causes manual transition to stop an active transition instead of being ignored
			requeueOnImageNotLoaded: true, // requeue the slideshow if any image slides are not yet loaded
			requeueTimeout: 250,  // ms delay for requeue
			activePagerClass: 'activeSlide', // class name used for the active pager link
			updateActivePagerLink: null // callback fn invoked to update the active pager link (adds/removes activePagerClass style)
		});
	}
	
	//Case Study Thymbnails
	var sliderSpeed = 2000;
	var sliderArea = J('#thumbnails-case-study #slidearea');
	var thumbContainer = J('#thumbnails-case-study #slider');
	var thumbs = J(thumbContainer).find('.thumb');
	if (J(thumbContainer).length && J(thumbs).length && J(sliderArea).length) {
		var thumbContainerWidth = 0;
		J(thumbs).fadeTo('fast',0.7);
		J(thumbs).hover(function(){
			J(this).stop();
			J(this).fadeTo('fast',1);
		},function(){
			J(this).stop();
			J(this).fadeTo('fast',0.7)
		});
		J(thumbs).each(function(){
			var w = parseInt(J(this).width());
			var pl = parseInt(J(this).css('padding-left'));
			var pr = parseInt(J(this).css('padding-right'));
			var ml = parseInt(J(this).css('margin-left'));
			var mr = parseInt(J(this).css('margin-right'));
			if (!w) w = 0;
			if (!pl) pl = 0;
			if (!pr) pr = 0;
			if (!ml) ml = 0;
			if (!mr) mr = 0;
			thumbContainerWidth += w+pl+pr+ml+mr;
		});
		J(thumbContainer).width(thumbContainerWidth);
		
		var sliderAreaWidth = parseInt(J(sliderArea).width());
		var minLeft = 0;
		var maxLeft = sliderAreaWidth-thumbContainerWidth;
		J('#slideleft').hover(function(){
			J(thumbContainer).stop();
			J(thumbContainer).animate({ 
				left: minLeft
			}, sliderSpeed, 'linear' );
		},function(){J(thumbContainer).stop();});
		J('#slideright').hover(function(){
			J(thumbContainer).stop();
			J(thumbContainer).animate({ 
				left: maxLeft
			}, sliderSpeed, 'linear' );
		},function(){J(thumbContainer).stop();});
	}
		
	//DropDown MENU
	if($('#uc_client_ddlClient')){
		$('#uc_client_ddlClient').append('<option value="0" selected="selected">Select Case Study</option>')
		$('#uc_client_ddlClient').attr('name', 'uc_client_ddlClient');
		$('#uc_client_ddlClient').attr('onchange', '');
		$('.select-case-study SELECT').jcombox({ fx: 'slideFade' });
								
		$('#uc_client_ddlClient .menu a').click(function(){				
			var redirect_url = $('#uc_client_ddlClient .menu a.current').attr('rel');
			top.location = redirect_url;
			return false;
		});		
	}
	$('.select-case-study .menu A[rel="0"]').remove();
	
	//Accordion (News & About Us)
	if ($('#accordion').length != 0){
		$('#accordion').accordion({header: ".accord-head"});
	}
	
	//Contact Us
	if ($("#buttonReset").length != 0 && $("#buttonSubmit").length != 0) {
		$("#buttonReset").click(function(){
			$("#txtName").attr("value","");
			$("#txtCompany").attr("value","");
			$("#txtTelephone").attr("value","");
			$("#txtEmail").attr("value","");
			$("#txtMessage").attr("value","");
			$(this).css("opacity","0.5");
			$(this).css("cursor","default");
			return false;
		});		
				
		inputKeypress();
		$(".picture INPUT[type=text]").keyup(function(){inputKeypress()});
		$(".picture TEXTAREA").keyup(function(){inputKeypress()});
	}
	
	//Slideshow
	if ($("#slideshow-container-jquery").length != 0) {
		setInterval("slideSwitch()", 10000);
	}
	
	//Contact Form
	if ( $("#buttonSubmit").length != 0 ) {
		$("#form1").submit(function(){
			//$("#RequiredFieldValidator1").css("left","10%");
			$("#RequiredFieldValidator1").animate({
				"left": "98%"
			}, "slow", "backinout" ,function(){			
			
				$("#RequiredFieldValidator6").animate({
					"left": "98%"
				}, "slow", "backinout",function(){
				
					$("#RequiredFieldValidator5").animate({
						"left": "98%"
					}, { "duration": "slow", "easing": "backinout" });
				
				});
			
			
			});
			

			//$("#RequiredFieldValidator6").animate( { left:"98%" }, { queue:false, duration:3000 } );
			//$("#RequiredFieldValidator5").animate( { left:"98%" }, { queue:false, duration:3000 } );

			return true;
		});
	}
});

function inputKeypress (){
	var isText = 0;
	J.each( J(".picture INPUT[type=text]"), function(i, n){
		if (J(n).val().length > 0) {isText = 1;}
	});
	if (J(".picture TEXTAREA").val().length > 0) {isText = 1;}
				
	if (isText) {J("#buttonReset").css("opacity","1");J("#buttonReset").css("cursor","pointer");}
	else {J("#buttonReset").css("opacity","0.5");J("#buttonReset").css("cursor","default");}
	isText = 0;
}

function slideSwitch() {
    var active = null;
    var next = null;
        
    active = J('#slideshow-container-jquery .active');
    next = active.next('.slideshow-thumbnail');

    if (next.length == 0) {
		next = J('#slideshow-container-jquery .slideshow-thumbnail:first');
	}

    if (J.browser.msie && J.browser.version.substr(0, 1) == '6') {
		active.css('display','none');
        active.removeClass('active');

        next.css('display', 'block');
        next.addClass('active');
            
	} else {		
		J(active).animate({opacity: 0.01}, 2000, function() { 			
			J(next).css('opacity','0.01');
			J(next).css('display','block');
			J(next).animate({opacity: 1}, 2000, function() { J(next).addClass('active'); });      
				
			J(active).removeClass('active'); 
			J(active).css('display','none');
		});
    }       
}



//Motools
window.addEvent('domready', function() {

    if ($('slideshow-container')) { 
        var obj = {
            wait: 3000,
            effect: 'fade',
            duration: 1000,
            loop: true,
            thumbnails: false,
            backgroundSlider: false
        }

        show = new SlideShow('slideshow-container', 'slideshow-thumbnail', obj);
        if ($('slideshow-container1')) {
            show1 = new SlideShow('slideshow-container1', 'slideshow-thumbnail1', obj);
            show2 = new SlideShow('slideshow-container2', 'slideshow-thumbnail2', obj);
        }

        show.play();
        if ($('slideshow-container1')) {
            show1.play();
            show2.play();
        }
    }

    if ($('pnslide')) {
        slidePress();
    }

    //mapView();

    if ($('light')) {
        Lightbox.init({ descriptions: '.lightboxDesc', showControls: false });
    }
	
});


function nextPageChange(nmb) {
	if ((nmb == null) && (nmb == undefined) ){ nmb = ''; }
	if ($('change' + nmb).getStyle('display') == 'block'){
		var myFx = new Fx.Style('change' + nmb, 'opacity');
		var myFx1 = new Fx.Style('onchange' + nmb, 'opacity');
		myFx.start(1,0).chain(function(){
			$('change' + nmb).setStyle('display', 'none');
            $('onchange' + nmb).setStyle('opacity', 0);
            $('onchange' + nmb).setStyle('display', 'block');
			myFx1.start(0,1);
			$('p1' + nmb).removeClass('page-sel');
			$('p2' + nmb).addClass('page-sel');
		});
	}
	
}

function prevPageChange(nmb) {
	if ((nmb == null) && (nmb == undefined) ){ nmb = ''; }
	if ($('onchange' + nmb).getStyle('display') == 'block'){
		var myFx = new Fx.Style('onchange' + nmb, 'opacity');
		var myFx1 = new Fx.Style('change' + nmb, 'opacity');
		myFx.start(1,0).chain(function(){
			$('onchange' + nmb).setStyle('display', 'none');
			$('change' + nmb).setStyle('display', 'block');
			myFx1.start(0,1);
			$('p2' + nmb).removeClass('page-sel');
			$('p1' + nmb).addClass('page-sel');
		});
	}
}

var slider = null;
function initErrMessage () {
	slider = new Fx.Slide('error-msg');
	slider.slideOut();
}

function ResetForm(){
	$('email-form').reset();
}

function SubmitForm(){
	initErrMessage();
	slider.slideOut();
	var fx = new Fx.Styles($('submit'), {duration: 500, wait: false});
	fx.start({'opacity': 0.5});
	$('email-form').send({update: null, onComplete: function (request) {FormCallback(request); }});

	return false;
}

function FormCallback(response){

	$('submit').setStyle('opacity', 1);
	if ((error = Process(response)) != ''){
		DisplayError(error);
	} else {
		SayThankYou();
	}
}

function DisplayError(msg){
	$('error-msg').setHTML('Error: ' + msg);
	slider.slideIn();
}

function Process(str){
	list = str.split(':');
	if(list[0].toLowerCase() != 'done'){
		return list[1];
	} else {
		return '';
	}
}

function SayThankYou(){
	$('error-msg').setHTML('');
	slider.slideOut();
	var fx = new Fx.Styles($('controls'), {duration: 500, wait: false});
	fx.start({'opacity': 0}).addEvent('onComplete', function(){
		var form = new Fx.Styles($('email-form'), {duration: 500, wait: false});
		form.start({'opacity': 0}).addEvent('onComplete', function (){
			$('email-form').setStyle('display', 'none');
			$('thank-you').setStyle('opacity', 0);
			$('thank-you').setStyle('display', 'block');
			var fxx = new Fx.Styles($('thank-you'), {duration: 500, wait: false});
			fxx.start({'opacity': 1});
		});
	});
}


function slidePress() {
	var effect = new Fx.Style('pnslide', 'marginLeft', {
	        duration: 500,
	        transition: Fx.Transitions.Sine.easeInOut
	    });
	$('slide_prev').addEvent('click', function(e){
		//e.stop();
	    var left = document.getElementById("pnslide").style.marginLeft;
	    if (left == "") left = 0;
	    if ((parseInt(left) != 0) && (parseInt(left) < 0)){
			effect.start(parseInt(left)+760);
		}
		
		if ((parseInt($('pnslide').getStyle('margin-left')) == 0) || (parseInt($('pnslide').getStyle('margin-left')) > -761)) {
			$('slide_prev').setStyle('display', 'none');
		}
		else {
			$('slide_prev').setStyle('display', 'block');
			$('slide_next').setStyle('display', 'block');
		}
		
	});
	$('slide_next').addEvent('click', function(e){
		//e.stop();
		if ($('last').getLeft() > 1000){
		    var left = document.getElementById("pnslide").style.marginLeft;
		    if (left == "") left = 0;
			effect.start(parseInt(left)-760);
		}
		
		if ($('last').getLeft() < 1750) {
			$('slide_next').setStyle('display', 'none');
		}
		else {
			$('slide_next').setStyle('display', 'block');
			$('slide_prev').setStyle('display', 'block');
		}

	});
	
	
	
}

function mapView() {
	$$('#map-links a').addEvent('click', function(e){
	//$('map-links').getElements('a').addEvent('click', function(e){
        var nm = $(this).getProperty('rel');

        var myFx = new Fx.Style(nm, 'opacity');
		$$('#brighton').setStyle('display', 'none');
		$$('#reading').setStyle('display', 'none');
		$$('#london').setStyle('display', 'none');
        $(nm).setStyle('display', 'block');
        myFx.start(0,1);
		$$('#map-links a').removeClass('m-sel');
		$(this).addClass('m-sel');
    });

}