//jQuey
var J = jQuery.noConflict();
J(document).ready(function($) {


    $('INPUT.auto-hint').each(function(i, el) {
        if ($(this).val() == '') {
            $(this).val($(this).attr('title'));
        }
        $(el).focus(function() {
            if ($(this).val() == $(this).attr('title')) {
                $(this).val('');
            }
        });
        $(el).blur(function() {
            if ($(this).val() == '') {
                $(this).val($(this).attr('title'));
            }
        });
    });

    //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 = 450;
    var sliderArea = J('#thumbnails-case-study #slidearea');
    var thumbContainer = J('#thumbnails-case-study #slider');
    var thumbs = J(thumbContainer).find('.thumb');
    //BEGIN: Preload Thumbs
    var imgs = J(thumbContainer).find('img');
    var countImgs = imgs.length;
    var loadedImgs = 0;
    J(imgs).each(function() {
        var src = J(this).attr('src');
        var img = new Image();
        J(img).load(function() {
            loadedImgs++;
            if (loadedImgs >= countImgs) imageSlider(sliderArea, thumbContainer, thumbs, sliderSpeed);
        }).attr('src', src);
    });
    //END: Preload Thumbs
    //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 && $("#eplContactUs_buttonSubmit").length != 0) {
        $("#buttonReset").click(function() {
            $("[id*=txtName]").attr("value", "");
            $("[id*=txtCompany]").attr("value", "");
            $("[id*=txtTelephone]").attr("value", "");
            $("[id*=txtEmail]").attr("value", "");
            $("[id*=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 ($("#eplContactUs_buttonSubmit").length != 0) {
    //        $("#form1").submit(function() {
    //            //$("#requiredfieldvalidator1").css("left","10%");
    //        $("[id*=Validator1]").animate(
    //            { "left": "-180%" }
    //            , "slow"
    //            , "backinout"
    //            , function() {
    //            $("[id*=Validator2]").animate(
    //                { "left": "-=98%" },
    //                "slow",
    //                "backinout",
    //                function() {
    //                    $("[id*=Validator6]").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;
    //        });
    //    }
    /*  BEGIN: Contact Us Form  */
    J('#contact_us, a[href*="contact-us.aspx"]').click(function() {
        setOverlay();
        var form = J('#contact-us-form');
        if (!J(form).length) return true;

        //find form
        var f = J('form', '#contact-us-form');
        if (!J(f).length) f = J('form', 'body');
        if (J(f).length) J(f)[0].reset();

        J('#fields').css('display', 'block');
        J('#contact-form-error').css('display', 'none');
        J('#contact-form-success').css('display', 'none');
        J(form).slideDown(1000);
        //ajaxFormSubmit(J('form'));
        J(".overlay, #buttonReset").click(function() {

            J(form).slideUp(1000, function() {
                J(".overlay").css('display', 'none');
                //J(".overlay").css({ 'background': '', 'opacity': '' });
                J('#page-scroll').css('overflow', '');
            });
            return false;
        });
        return false;
    });
    /*  END: Contact Us Form  */


    J('.search-bar select').each(function() { J(this).attr("name", J(this).attr("id")); });
    J('.search-bar select').jcombox({ fx: 'slideFade' });
    J('.search-bar .menu a').click(function(event) {
        var redirect_url = J(this).attr('rel');

        // alert(redirect_url);
        if (redirect_url != 'none') {
            window.document.location = redirect_url;
            event.cancelBubble = true;
            if (event.stopPropagation)
                event.stopPropagation();
        }
        return false;
    });
});
function ajaxFormSubmit(form){
    J(form).submit(function() {
        J('#contact-form-loader').css('display', 'block');
        J('#contact-form-error').slideUp('fast');
        J('#contact-form-success').slideUp('fast');
        alert(J(this).serialize());
        J.ajax({
            type: "POST",
            url: J(form).attr('action'),
            data: J(this).serialize(),
            success: function(response) {
                J('#contact-form-loader').css('display', 'none');
                var error = response.split(':');
                if (error && error.length > 1 && error[0] == 'ERROR') {
                    J('#contact-form-error').html(error[1]);
                    J('#contact-form-error').slideDown('fast');
                } else {
                    J('#fields').slideUp('slow', function() {
                        J('#contact-form-success').html(response);
                        J('#contact-form-success').slideDown('fast');
                    });
                }
            }
        });
        return false;
    });
}
J(window).resize(function() {
	if (J(".overlay:visible").length) {
		J(".overlay:visible").width('');
		J(".overlay:visible").height('');
		setOverlay();
	}
});
function setOverlay(){
	var width = (J.browser.msie && J.browser.version == '6.0')?(J(document).width()-20):J(document).width();
	J(".overlay").height(J(document).height()).width(width).css('display','block');
	J('#page-scroll').css('overflow','hidden');
	//J(".overlay").css('display','block');
}
function imageSlider(sliderArea,thumbContainer,thumbs,sliderSpeed) {
	J('#slideleft,#slideright').mousedown(function(){return false;});
	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;
		if (maxLeft >= 0) return false;
		/*  BEGIN: Slide On Click*/
		var step = 1;
		var process = false;
		var thumbWidth = parseInt(J(thumbs).width());
		var cssLeftMin = 0;
		var cssLeftMax = maxLeft;
		J('#slideleft').click(function(){
			if (process) return false;
			process = true;
			var cssLeftCurr = parseInt(J(thumbContainer).css('left'));
			var cssLeftNext = cssLeftCurr+step*thumbWidth;
			if (cssLeftNext > cssLeftMin) cssLeftNext = cssLeftMin;
			//Move last thumb to the begin
			/*if (cssLeftNext > cssLeftMin) {
				for (var i = 0;i < step;i++) {
					var lastThumb = J(thumbContainer).find('.thumb:last[rel!=deleted]');
					var left = parseInt(J(thumbContainer).css('left'));
					J(thumbContainer).css('left',left-thumbWidth)
					cssLeftNext = cssLeftNext - thumbWidth;
					//BEGIN: Set New Width
					var thumbContainerWidth = parseInt(J(thumbContainer).width())+getThumbWidth(lastThumb);
					J(thumbContainer).width(thumbContainerWidth);
					//END: Set New Width
					J(thumbContainer).prepend(J(lastThumb).clone());
					J(lastThumb).attr('rel','deleted');
				}
			}*/
			J(thumbContainer).stop();
			J(thumbContainer).animate({ 
				left: cssLeftNext
			}, sliderSpeed, 'easeInCubic',function(){
				//BEGIN:Remove Copied thumbnails
				/*copiedThumbnail = J(thumbContainer).find('.thumb[rel=deleted]');
				J(copiedThumbnail).each(function(){
					var thumbContainerWidth = parseInt(J(thumbContainer).width())-getThumbWidth(this);
					J(this).remove();
					J(thumbContainer).width(thumbContainerWidth);
				});*/
				//END:Remove Copied thumbnails
				process = false;
			} );
		});
		J('#slideright').click(function(){
			if (process) return false;
			process = true;
			var cssLeftCurr = parseInt(J(thumbContainer).css('left'));
			var cssLeftNext = cssLeftCurr-(step*thumbWidth);
			if (cssLeftNext < cssLeftMax) cssLeftNext = cssLeftMax;
			//Move last thumb to the begin
			/*if (cssLeftNext < cssLeftMax) {
				//var required = Math.round((cssLeftMax - cssLeftNext)/thumbWidth);
				for (var i = 0;i < step;i++) {
					var firstThumb = J(thumbContainer).find('.thumb:first[rel!=deleted]');
					var left = parseInt(J(thumbContainer).css('left'));
					//J(thumbContainer).css('left',left+thumbWidth);
				
					//cssLeftNext = cssLeftNext - thumbWidth;
					//BEGIN: Set New Width
					var thumbContainerWidth = parseInt(J(thumbContainer).width())+getThumbWidth(firstThumb);
					J(thumbContainer).width(thumbContainerWidth);
					//END: Set New Width
					J(thumbContainer).append(J(firstThumb).clone());
					J(firstThumb).attr('rel','deleted');
				}
			}*/
			J(thumbContainer).stop();
			J(thumbContainer).animate({ 
				left: cssLeftNext
			}, sliderSpeed, 'easeInCubic',function(){
				//BEGIN:Remove Copied thumbnails
				/*copiedThumbnail = J(thumbContainer).find('.thumb[rel=deleted]');
				J(copiedThumbnail).each(function(){
					var thumbContainerWidth = parseInt(J(thumbContainer).width())-getThumbWidth(this);
					J(this).remove();
					J(thumbContainer).width(thumbContainerWidth);
				});
				J(thumbContainer).css('left','0px');*/
				//END:Remove Copied thumbnails
				process = false;
			} );
		});
		/*  END: Slide On Click*/
	}
}
function getThumbWidth(thumb){
	var w = parseInt(J(thumb).width());
	var pl = parseInt(J(thumb).css('padding-left'));
	var pr = parseInt(J(thumb).css('padding-right'));
	var ml = parseInt(J(thumb).css('margin-left'));
	var mr = parseInt(J(thumb).css('margin-right'));
	if (!w) w = 0;
	if (!pl) pl = 0;
	if (!pr) pr = 0;
	if (!ml) ml = 0;
	if (!mr) mr = 0;
	var width = w+pl+pr+ml+mr;
	return width;
}
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

if ($ != 'undefined' && $ != null) {
    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;

