/***** JQUERY SWFOBJECT *****/

(function(f,h,i){function k(a,c){var b=(a[0]||0)-(c[0]||0);return b>0||!b&&a.length>0&&k(a.slice(1),c.slice(1))}function l(a){if(typeof a!=g)return a;var c=[],b="";for(var d in a){b=typeof a[d]==g?l(a[d]):[d,m?encodeURI(a[d]):a[d]].join("=");c.push(b)}return c.join("&")}function n(a){var c=[];for(var b in a)a[b]&&c.push([b,'="',a[b],'"'].join(""));return c.join(" ")}function o(a){var c=[];for(var b in a)c.push(['<param name="',b,'" value="',l(a[b]),'" />'].join(""));return c.join("")}var g="object",m=true;try{var j=i.description||function(){return(new i("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version")}()}catch(p){j="Unavailable"}var e=j.match(/\d+/g)||[0];f[h]={available:e[0]>0,activeX:i&&!i.name,version:{original:j,array:e,string:e.join("."),major:parseInt(e[0],10)||0,minor:parseInt(e[1],10)||0,release:parseInt(e[2],10)||0},hasVersion:function(a){a=/string|number/.test(typeof a)?a.toString().split("."):/object/.test(typeof a)?[a.major,a.minor]:a||[0,0];return k(e,a)},encodeParams:true,expressInstall:"expressInstall.swf",expressInstallIsActive:false,create:function(a){if(!a.swf||this.expressInstallIsActive||!this.available&&!a.hasVersionFail)return false;if(!this.hasVersion(a.hasVersion||1)){this.expressInstallIsActive=true;if(typeof a.hasVersionFail=="function")if(!a.hasVersionFail.apply(a))return false;a={swf:a.expressInstall||this.expressInstall,height:137,width:214,flashvars:{MMredirectURL:location.href,MMplayerType:this.activeX?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}attrs={data:a.swf,type:"application/x-shockwave-flash",id:a.id||"flash_"+Math.floor(Math.random()*999999999),width:a.width||320,height:a.height||180,style:a.style||""};m=typeof a.useEncode!=="undefined"?a.useEncode:this.encodeParams;a.movie=a.swf;a.wmode=a.wmode||"opaque";delete a.fallback;delete a.hasVersion;delete a.hasVersionFail;delete a.height;delete a.id;delete a.swf;delete a.useEncode;delete a.width;var c=document.createElement("div");c.innerHTML=["<object ",n(attrs),">",o(a),"</object>"].join("");return c.firstChild}};f.fn[h]=function(a){var c=this.find(g).andSelf().filter(g);/string|object/.test(typeof a)&&this.each(function(){var b=f(this),d;a=typeof a==g?a:{swf:a};a.fallback=this;if(d=f[h].create(a)){b.children().remove();b.html(d)}});typeof a=="function"&&c.each(function(){var b=this;b.jsInteractionTimeoutMs=b.jsInteractionTimeoutMs||0;if(b.jsInteractionTimeoutMs<660)b.clientWidth||b.clientHeight?a.call(b):setTimeout(function(){f(b)[h](a)},b.jsInteractionTimeoutMs+66)});return c}})(jQuery,"flash",navigator.plugins["Shockwave Flash"]||window.ActiveXObject);

//$.flash.expressInstaller = 'myFlashPath/expressInstall.swf';

/***** EASING *****/

jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeInOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInExpo:function(e,f,a,h,g){return(f===0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f===0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInRegular:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutRegular:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutRegular:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a}});

/**
 * http://detectmobilebrowser.com/
 * jQuery.browser.mobile will be true if the browser is on a mobile device
 **/
(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

/***** MOUSEWHEEL LISTENER *****/

(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(i){var g=i||window.event,f=[].slice.call(arguments,1),j=0,h=true,e=0,d=0;i=c.event.fix(g);i.type="mousewheel";if(i.wheelDelta){j=i.wheelDelta/120}if(i.detail){j=-i.detail/3}d=j;if(g.axis!==undefined&&g.axis===g.HORIZONTAL_AXIS){d=0;e=-1*j}if(g.wheelDeltaY!==undefined){d=g.wheelDeltaY/120}if(g.wheelDeltaX!==undefined){e=-1*g.wheelDeltaX/120}f.unshift(i,j,e,d);return c.event.handle.apply(this,f)}})(jQuery);

/***** DragThrow (With Touch!) Author: Miles Spoor 2011 *****/

(function($) {

    $.fn.dragThrow = function(options) {

        var settings = {
            "axis" : "both",
            "ticks" : 15,
            "dragging": undefined,
            "throwing": undefined,
            "end": undefined,
            "clicker": undefined
        }
        return this.each(function() {
            
            
            if(options){
                $.extend(settings, options);   
            }
            
            var $this = $(this), currentX = 0, currentY = 0, lastX = currentX, lastY = currentY, vx = currentX - lastX, vy = currentY - lastY, curX = 0, curY = 0, offsetX = 0, offsetY = 0, dragging = false, timer, intval = "", moved = false;
            
            function stopPhysics(){
                if(intval!==""){
                    window.clearInterval(intval);
                    intval="";
                }
            }
          
            function startPhysics(){
                if(intval==""){
                    intval=window.setInterval(function(){
                        if(dragging == false && (vx !== 0 || vy !== 0)){
                            if(settings.throwing !== undefined){
                                settings.throwing();
                            }
                            if(vx > 100){
                                vx = 100;  
                            }
                            if(vx < -100){
                                vx = -100;
                            }
                            
                            if(vy > 100){
                                vy = 100;  
                            }
                            if(vy < -100){
                                vy = -100;
                            }
                            
                            if(settings.axis == "x" || settings.axis == "both"){
                                $this.css("left", parseFloat($this.css("left")) + vx);
                            }
                            if(settings.axis == "y" || settings.axis == "both"){
                                $this.css("top", parseFloat($this.css("top")) + vy);
                            }
                            vx *= 0.95;
                            vy *= 0.95;
                            if(Math.floor(vx) == -1 || Math.floor(vx) == 0){
                                vx = 0;
                            }
                            if(Math.floor(vy) == -1 || Math.floor(vy) == 0){
                                vy = 0;
                            }
                        }else if(dragging == false && vx == 0 && vy == 0){
                            stopPhysics();
                        }
                    },settings.ticks)
                }
            };
            
            $this.css({"position": "absolute"});
            
            $this.parent().css("position", "relative");
            if(navigator.platform.indexOf("iPhone") !== -1 || navigator.platform.indexOf("iPad") !== -1 || navigator.platform.indexOf("iPod") !== -1){
                $this.find("li").live("touchstart", mouserTouchDown);
                $this.find("li").live("touchmove", mouserTouchMove);
                $this.find("li").live("touchend", mouserTouchUp);
            }else{
                $this.find("li").delegate("mousedown", mouserDown);
                $(document).delegate("mouseup", mouserUp);
                $(document).delegate("mousemove", mouserMove);
				$this.ondragstart = function() {return false;};
            }
			
            function mouserMove(e){
                if(dragging){
                    if(settings.dragging !== undefined){
                        settings.dragging();
                    }
                    moved = true
                    if(settings.axis == "x" || settings.axis == "both"){
                        $this.css("left", (offsetX + e.pageX  - curX) + 'px');
                        lastX = currentX;
                        currentX = $this.css("left") !== "auto" ? parseFloat($this.css("left")): 0;
                        vx = currentX - lastX;
                    }
                    if(settings.axis == "y" || settings.axis == "both"){
                        $this.css("top", (offsetY + e.pageY  - curY) + 'px');
                        lastY = currentY;
                        currentY = $this.css("top") !== "auto" ? parseFloat($this.css("top")): 0;
                        vy = currentY - lastY;
                    }
                }
            }
            function mouserUp(e){
                dragging = false;
                startPhysics();
                if(moved == false && settings.click !== undefined){
                    settings.click();
                }else{
                    e.preventDefault(); 
                    return false;
                }
            }
            function mouserDown(e){
                moved = false
                dragging = true;
                
                if(settings.axis == "x" || settings.axis == "both"){
                    curX = e.pageX;
                    vx = 0;
                    offsetX = $this.css("left") !== "auto" ? parseFloat($this.css("left")):0;
                }
                if(settings.axis == "y" || settings.axis == "both"){
                    curY = e.pageY;
                    vy = 0;
                    offsetY = $this.css("top") !== "auto" ? parseFloat($this.css("top")):0;
                }
            }
            
            function mouserTouchDown(e){
                moved = false
                var orig = e.originalEvent;
                e.preventDefault();
                dragging = true;
                if(settings.axis == "x" || settings.axis == "both"){
                    curX = orig.changedTouches[0].pageX;
                    vx = 0;
                    offsetX = $this.css("left") !== "auto" ? parseInt($this.css("left")):0;
                }
                
                if(settings.axis == "x" || settings.axis == "both"){
                    curY = orig.changedTouches[0].pageY;
                    vy = 0;
                    offsetY = $this.css("top") !== "auto" ? parseInt($this.css("top")):0;
                }
				return false;
            }
            
            function mouserTouchMove(e){
                if(dragging){
                    if(settings.dragging !== undefined){
                        settings.dragging();
                    }
                    moved = true;
                    e.preventDefault();
                    var orig = e.originalEvent;
                    if(settings.axis == "x" || settings.axis == "both"){
                        $this.css("left", (offsetX + orig.changedTouches[0].clientX- curX) + 'px');
                        lastX = currentX;
                        currentX = $this.css("left") !== "auto" ? parseFloat($this.css("left")): 0;
                        vx = currentX - lastX;
                    }
                    
                    if(settings.axis == "y" || settings.axis == "both"){
                        $this.css("top", (offsetY + orig.changedTouches[0].clientY- curY) + 'px');
                        lastY = currentY;
                        currentY = $this.css("top") !== "auto" ? parseFloat($this.css("top")): 0;
                        vy = currentY - lastY;
                    }
                }
            }
            
            function mouserTouchUp(e){
                dragging = false;
                if(moved == false){
                    if(typeof(settings.clicker) == "function"){
                        settings.clicker();
                    }
					document.location.href = $(this).find("a").attr("href");
                }else{
					startPhysics();
                    e.preventDefault();
                    return false;
                }
            }
			
        });

    };
})(jQuery);

/***** jQuery reverse $("selecteor").reverse(); Returns revered array. *****/

$.fn.reverse = [].reverse;

/***** WICKEDWEB LIGHTBOX v1.2 | COPYRIGHT WICKEDWEB 2011 *****/

var lbSrc = "";
var galleryArray = [];
var imgNo = 0;
var lbStatus = 'closed';

String.prototype.endsWith = function(b){
    return (this.match(b + "$") == b);
};

function querySt(value, string){
    valueArray = string.split('?').join('&').split('&amp;').join('&').split('&');
    for(i = 0; i < valueArray.length; i++){
        result = valueArray[i].split('=');
        if(result[0] == value){
            return result[1];
        }
    }
}

function repositionLightBox(){
	if(($('#lightBoxInner').outerHeight() + 80) > $(window).height() && $('#lightBox:visible').size() > 0){
		$('#lightBoxContent').css({top:($(window).scrollTop() + 20) + 'px', position:'absolute', marginTop:0});
	}
	else{
		$('#lightBoxContent').css({top:'50%', position:'fixed', marginTop:-($('#lightBoxInner').outerHeight() / 2) - 20});
	}
}

function animateLightBox(){
    $('#lightBoxInner').not($('#lightBoxInner:has(#closeLightBoxBtn)')).prepend('<a href="/Close" id="closeLightBoxBtn" class="closeLightBox"></a>');
    var mTop = -($('#lightBoxInner').outerHeight() / 2) - 20;
    var mLft = -($('#lightBoxInner').outerWidth() / 2) - 50;
    $('#lightBoxContent').stop().animate({
        width: $('#lightBoxInner').outerWidth(),
        height: $('#lightBoxInner').outerHeight(),
        marginTop: mTop,
        marginLeft: mLft,
        opacity: 1
    },{duration: 600,
        easing: "easeInOutRegular",
        step: function(){
            $('#lbtl,#lbtr,#lbbl,#lbbr,').hide().show();
			if(($('#lightBoxContent').outerHeight() + 80) > $(window).height()){
				$('#lightBoxContent').css({top:($(window).scrollTop() + 20) + 'px', position:'absolute', marginTop:0});
				mTop = 0;
			}
			else{
				$('#lightBoxContent').css({top:'50%', position:'fixed'});
				mTop -($('#lightBoxInner').outerHeight() / 2);
			}
        },
		complete: function(){
            repositionLightBox();
            $('#lightBoxContent').css({filter:''});
            $('#lightBoxInner').css({visibility:'visible'});
            $('#lightBoxInner').stop().fadeTo(500, 1, function(){
                $('#lightBoxContent, #lightBoxInner').css({filter:''});
            });
        }
    });
}

function detectContent(){
	if(lbStatus == 'content'){
		$('#lightBoxInner > div:first').hide().appendTo('body');
	}
    $('#lightBoxInner').empty();
    $('#lightBoxInner').css({width:'auto', height:'auto'});
	$('#lightBoxContent').css({overflow:'hidden', marginTop:-($('#lightBoxContent').outerHeight() / 2) + 'px', marginLeft:-($('#lightBoxContent').outerWidth() / 2) + 'px'});
    var Title = querySt('title', lbSrc);
    var Desc = querySt('desc', lbSrc);
    var Width = querySt('width', lbSrc);
    var Height = querySt('height', lbSrc);
    var Close = querySt('close', lbSrc);
    var Lat = querySt('lat', lbSrc);
    var Lang = querySt('lang', lbSrc);
	var Zoom = querySt('zoom', lbSrc);
    if(Width !== undefined){
        $('#lightBoxInner').width(parseInt(Width));
    }
    if(Height !== undefined){
        $('#lightBoxInner').height(parseInt(Height));
    }
    if(Title !== undefined){
        $('#lightBoxInner').append('<h1>' + Title + '</h1>');
    }
    if(Desc !== undefined){
        $('#lightBoxInner').append(Desc);
    }
    if(lbSrc.indexOf('?') > -1) {
        lbSrc = lbSrc.slice(0, lbSrc.indexOf('?'));
    }
    if(Close == 'false'){
        $('body').addClass('noClose');
        $('#lightBox').removeClass('closeLightBox');
    }
    else{
        $('body').removeClass('noClose');
        $('#lightBox').addClass('closeLightBox');
    }
    r = document.location.href.toString().replace(document.location.hash.toString(), '');
    if(lbSrc.indexOf('?') > -1){
        q = lbSrc.slice(lbSrc.indexOf('?'));
        lbSrc = lbSrc.slice(0, lbSrc.indexOf('?'));
    }
    if(lbSrc.indexOf(r) === 0){
        lbSrc = lbSrc.replace(r, '');
    }
    if(Lat !== undefined && Lang !== undefined){
        $('#lightBoxInner').append('<div id="map" style="width:' + Width + 'px; height:' + Height + 'px;"></div>');
        var latlng = new google.maps.LatLng(Lat, Lang);
        var myOptions = {
            zoom: 16,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"), myOptions);
        //var image = 'imagesbeachflag.png';
        var beachMarker = new google.maps.Marker({
            position: latlng,
            map: map//,
            //icon: image
        });
        animateLightBox();
        lbStatus = 'content';
    }
    else if(lbSrc.indexOf('#') === 0){
        $(lbSrc).clone(true).appendTo('#lightBoxInner').show();
        animateLightBox();
        lbStatus = 'content';
    }
	else if(lbSrc.indexOf('http://vimeo.com') > -1){
		if(lbStatus == 'closed'){
            $('#lightBoxInner').css({width:'100px', height:'100px'});
            animateLightBox();
        }
		var vidURL = lbSrc.replace('http://vimeo.com/', '');
		$('#lightBoxInner').css({width:'640px', height:'360px'}).append('<iframe src="http://player.vimeo.com/video/'+vidURL+'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="640" height="360" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>');
		animateLightBox();
		lbSrc = 'video';
	}
    else if(lbSrc.endsWith('.html') || lbSrc.endsWith('.htm') || lbSrc.endsWith('.php') || lbSrc.endsWith('.aspx')){
        $('#lightBoxMid').addClass('loading');
        if(lbStatus == 'closed'){
            animateLightBox();
        }
        $('#lightBoxInner').load(lbSrc, function(){
			if(Width == undefined){
				Width = 920;
			}
			$('#lightBoxInner').width(Width);
            $('#lightBoxMid').removeClass('loading');
            animateLightBox();
            lbStatus = 'html';
        });
    }
    else if(lbSrc.endsWith('.jpg') || lbSrc.endsWith('.gif') || lbSrc.endsWith('.png') || lbSrc.endsWith('.bmp') || lbSrc.endsWith('.tiff')){
        $('#lightBoxMid').addClass('loading');
        if(lbStatus == 'closed'){
            $('#lightBoxInner').css({width:'100px', height:'100px'});
            animateLightBox();
        }
        var img = "img" + lbSrc.slice(lbSrc.lastIndexOf("/") + 1, lbSrc.lastIndexOf("."));
        eval[img] = new Image();
        eval[img].onload = function (evt){
            $('#lightBoxInner').fadeTo(0, 0, function(){
                if(Width !== undefined){
                    eval[img].width = parseInt(Width);
                }
                if(Height !== undefined){
                    eval[img].height = parseInt(Height);
                }
                $('#lightBoxInner').css({width:eval[img].width + 'px', height:eval[img].height + 'px'}).prepend(eval[img]);
                if(galleryArray.length > 1){
                    $('#lightBoxInner').append('<a href="/Previous" class="prevImg"></a><a href="/Next" class="nextImg"></a>');
                }
                $('#lightBoxMid').removeClass('loading');
                animateLightBox();
                lbStatus = 'image';
            });
        };
        eval[img].src = lbSrc;
        imgNo = jQuery.inArray(lbSrc, galleryArray);
    }
	else if(lbSrc.endsWith('.pdf')){
		if(Width == undefined){
			Width = 920;
		}
		if(Height == undefined){
			Height = 500;
		}
		if(lbSrc.indexOf('http://') == -1){
		    lbSrc = [document.location.protocol, '//', document.location.host].join('') + lbSrc + '#toolbar=0';
		}
		if(Zoom !== undefined){
			lbSrc += '&zoom=' + Zoom;
		}
		$('#lightBoxInner').css({width:Width + 'px', height:Height + 'px'}).append('<iframe src="' + lbSrc + '" width="' +  Width + '" height="' +  Height + '" frameborder="0"></iframe>');
		animateLightBox();
	}
}

function showLightBox(){
    $('#lightBoxInner').css({visibility:'hidden'});
    if($('#lightBoxContent:visible').size() > 0){
        detectContent();
    }
    else{
        $('#lightBox').stop().show().fadeTo(0, 0).fadeTo(500, 0.6, function(){
            $('#lightBoxContent').stop().show().fadeTo(0, 0, function(){
                detectContent();
            });
        });
    }
}

function openLightBox(s){
    lbSrc = s;
    if($('#lightBoxContent:visible').size() > 0){
        $('#lightBoxInner').stop().fadeTo(500, 0, function(){
            showLightBox();
        });
    }
    else{
        $('#lightBoxInner').fadeTo(0, 0, function(){
            showLightBox();
        });
    }
}

function gallery(){
    galleryArray = [];
    $('.lightBox[href$=".jpg"], .lightBox[href$=".gif"], .lightBox[href$=".png"], .lightBox[href$=".bmp"], .lightBox[href$=".tiff"]').each(function(){
        var inArray = false;
        var url = $(this).attr('href');
        if(jQuery.inArray(url, galleryArray) === -1){
            galleryArray.push(url);
        }
    });
    $('a[rel$=".jpg"], a[rel$=".gif"], a[rel$=".png"], a[rel$=".bmp"], a[rel$=".tiff"]').each(function(){
        var inArray = false;
        var url = $(this).attr('rel');
        if(jQuery.inArray(url, galleryArray) === -1) {
            galleryArray.push(url);
        }
    });
}

function closeLightBox(){
    $('#lightBoxMid').removeClass('loading');
    $('#lightBoxContent').stop().fadeTo(500, 0, function(){
        $('#lightBox').stop().fadeTo(500, 0, function(){
            $('#lightBox').addClass('closeLightBox');
			$('#lightBox, #lightBoxContent').removeAttr('style').removeAttr('filter');
			if(lbStatus == 'content'){
				$('#lightBoxInner > div:first').hide().appendTo('body');
			}
            $('#lightBoxInner').empty();
            $('body.noClose').removeClass('noClose');
            lbStatus = 'closed';
        });
    });
}

function initWWightBox(){
	$('body').append('<div id="lightBox" class="closeLightBox"></div><div id="lightBoxContent"><div id="lightBoxMid"><div id="lightBoxInner"></div></div></div>');
	lbSrc = querySt('lb', window.location.search);
	if(lbSrc != undefined){
		if(lbSrc.indexOf('.') == -1){
			lbSrc = '#' + lbSrc;
		}
		openLightBox(lbSrc + '?' + window.location.search);
	}
    $(window).resize(function(){
        repositionLightBox();
    });
    gallery();
}

function prevImage(){
    imgNo--;
    if(imgNo < 0){
        imgNo = galleryArray.length - 1;
    }
    openLightBox(galleryArray[imgNo]);
}

function nextImage(){
    imgNo++;
    if(imgNo > (galleryArray.length - 1)){
        imgNo = 0;
    }
    openLightBox(galleryArray[imgNo]);
}


$('.lightBox').live('click', function(e){
	openLightBox($(this).attr('href'));
	return false;
});

$('.closeLightBox').live('click', function(){
    closeLightBox();
    return false;
});

$('.prevImg').live('click', function(){
    prevImage();
    return false;
});

$('.nextImg').live('click', function(){
    nextImage();
    return false;
});

$(document).keyup(function(event){
    if(lbStatus != 'closed' && event.keyCode == '27'){
        event.preventDefault();
        closeLightBox();
    }
    else if(lbStatus == 'image' && (event.keyCode == '37' || event.keyCode == '80')){
        event.preventDefault();
		if(galleryArray.length > 1){
        	prevImage();
		}
    }
    else if(lbStatus == 'image' && (event.keyCode == '39' || event.keyCode == '78')){
        event.preventDefault();
		if(galleryArray.length > 1){
        	nextImage();
		}
    }
    else if(lbStatus == 'image' && ((parseInt(event.keyCode)) > 48 && (parseInt(event.keyCode)) < 58)){
        if((9 - (58 - (parseInt(event.keyCode)))) != imgNo){
            imgNo = (9 - (58 - (parseInt(event.keyCode))));
            if(imgNo > (galleryArray.length - 1)){
                imgNo = (galleryArray.length - 1);
            }
            openLightBox(galleryArray[imgNo]);
        }
    }
    else if(lbStatus == 'image' && ((parseInt(event.keyCode)) > 96 && (parseInt(event.keyCode)) < 106)){
        if((9 - (106 - (parseInt(event.keyCode)))) != imgNo){
            imgNo = (9 - (106 - (parseInt(event.keyCode))));
            if(imgNo > (galleryArray.length - 1)){
                imgNo = (galleryArray.length - 1);
            }
            openLightBox(galleryArray[imgNo]);
        }
    }
});

$(function(){
	initWWightBox();
	$('#rightColumn .rightArrow a').attr('target', '_blank');
});

/***** BACKGROUND ANIMATIONS *****/

(function(b){if(!document.defaultView||!document.defaultView.getComputedStyle){var d=jQuery.curCSS;jQuery.curCSS=function(g,e,h){if(e==="background-position"){e="backgroundPosition"}if(e!=="backgroundPosition"||!g.currentStyle||g.currentStyle[e]){return d.apply(this,arguments)}var f=g.style;if(!h&&f&&f[e]){return f[e]}return d(g,"backgroundPositionX",h)+" "+d(g,"backgroundPositionY",h)}}var c=b.fn.animate;b.fn.animate=function(e){if("background-position" in e){e.backgroundPosition=e["background-position"];delete e["background-position"]}if("backgroundPosition" in e){e.backgroundPosition="("+e.backgroundPosition}return c.apply(this,arguments)};function a(f){f=f.replace(/left|top/g,"0px");f=f.replace(/right|bottom/g,"100%");f=f.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");var e=f.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);return[parseFloat(e[1],10),e[2],parseFloat(e[3],10),e[4]]}b.fx.step.backgroundPosition=function(f){if(!f.bgPosReady){var h=b.curCSS(f.elem,"backgroundPosition");if(!h){h="0px 0px"}h=a(h);f.start=[h[0],h[2]];var e=a(f.options.curAnim.backgroundPosition);f.end=[e[0],e[2]];f.unit=[e[1],e[3]];f.bgPosReady=true}var g=[];g[0]=((f.end[0]-f.start[0])*f.pos)+f.start[0]+f.unit[0];g[1]=((f.end[1]-f.start[1])*f.pos)+f.start[1]+f.unit[1];f.elem.style.backgroundPosition=g[0]+" "+g[1]}})(jQuery);

function setCSS(css){
	try{
		document.write(css);
	}catch(e){
		setTimeout(function(){setCSS(css);}, 10);
	}
}

var css = '<style id="jscss" type="text/css">#overlay{opacity:1;filter:alpha(opacity=100);}</style>';
if(navigator.platform.indexOf("iPad")>=0 || jQuery.browser.mobile){
	css = '<style id="jscss" type="text/css">#background img{display:none;} #overlay{opacity:1;filter:alpha(opacity=100);}</style>';
}
setCSS(css);
css = null;

function dropdown(target){
	// Make fading of the name and the arrow independent for the parent?
	
	var lowestParent = Infinity; //Infinity isnt wokring anymore;
	var currentParent;
	
	$("li", target).each(function(){
		if($(this).attr("class").match(/sub[0-9]{1,3}/) == null){
			$(this).addClass("sub999");
		}
		var sub = parseInt($(this).attr("class").match(/sub[0-9]{1,3}/)[0].replace("sub", ""));
		if(sub<lowestParent){lowestParent = sub;}
	});
	
	$("li", target).each(function(){
		var sub = parseInt($(this).attr("class").match(/sub[0-9]{1,3}/)[0].replace("sub", ""));
		if(sub==lowestParent){
			currentParent = $(this);
			$(this).css("position", "relative");
			$(this).append("<div><ul></ul></div>");
			$(this).append('<div class="arrowBtn"></div>');
		}else{
			var classes = $(this).attr("class");
			$("div ul", currentParent).append('<li class="'+classes+'">'+$(this).html()+'</li>');
			$(this).remove();
		}
	});
	$(".arrowBtn", target).fadeTo(0, 0.65);
	$(target).children("li").each(function(){
		if($(this).find("ul li").length == 0){
			$(this).find("div").remove();
		}else{
			$(this).addClass("parent");
			$(this).unbind("mouseover mouseout").css("background-position", "0px 0px");
			$(this).children("a").click(function(){
				if($(this).attr("href") == undefined){
					$(this).parents(".parent").children(".arrowBtn").click();
				}
			})
		}
	});
	$("li .arrowBtn", target).click(function(){
		if(!$(this).parent().hasClass("clicked")){
			$(this).css("background-position", "center bottom");
			$(".clicked div ul").stop().animate({
				height:0
			}, 300);
			$(".clicked .arrowBtn", target).css("background-position", "center top").stop().fadeTo(150, 0.65);
			$(".clicked", target).children("a").fadeTo(150, 0.65);
			$(".clicked", target).removeClass("clicked");
			$(this).parent().addClass("clicked");
			var heightTo =  findHeight($(this).prev().find("ul"))+10;
			$(this).parents("li").find("div ul").stop().animate({
				height: heightTo+10
			},300);
			$(this).parent().children("a").fadeTo(150, 1);
			$(this).stop().fadeTo(150, 1);
		}else{
			$(this).parent().removeClass("clicked");
			$(this).css("background-position", "center top");
			$(this).parents("li").find("div ul").stop().animate({
				height: 0
			},300);
			$(this).parent().children("a").stop().fadeTo(150, 0.65);
			$(this).stop().fadeTo(150, 0.65);
		}
	});
	$(target).find("li").bind("mouseover", function(){
		$(this).children("a").stop().fadeTo(150, 1);
		$(this).children(".arrowBtn").stop().fadeTo(150, 1);
	})
	$(target).find("li").bind("mouseout", function(){
		if(!$(this).hasClass("clicked")){
			$(this).children("a").stop().fadeTo(150, 0.65);
			$(this).children(".arrowBtn").stop().fadeTo(150, 0.65);
		}
	});
	if($(".on", target).length !== 0){
		if(!$(".on", target).hasClass("parent")){
				if(!$(".on", target).hasClass("sub"+lowestParent)){
					//Not sub sub children (sub4) consider amending
					
					$(".on", target).not(".sub4").css("background", "url(/static/images/leftnav_arrow.png) 6px 9px no-repeat");
					$(".on", target).parents(".parent").find(".arrowBtn").click();
					$(".on", target).parents(".parent").unbind("mouseover mouseout");
				}
		}else{
			$(".on", target).find(".arrowBtn").click();	
		}
		if($(".on", target).find("li").length == 0){
			$(".on", target).unbind("mouseover mouseout");
		}
	}
}
function imageSliderPeople(){
	$("#people-drag").css("width", $("#people-drag").find("li").length * $("#people-drag").find("li").first().width()+"px");
	
	function checkOffScreen(){
		if(parseInt($("#people-drag").css("left")) + parseInt($("#people-drag").css("margin-left")) > -166*8){
			$("#people-drag").find("li").last().clone(true, true).prependTo($("#people-drag").find("ul"));
			$("#people-drag").find("li").last().remove();
			$("#people-drag").css("margin-left", (parseInt($("#people-drag").css("margin-left"))-166)+"px" );
		}else if(parseInt($("#people-drag").css("left")) + parseInt($("#people-drag").css("margin-left")) + $("#people-drag").width() < $("#people-thumb").width()+166*8){
			$("#people-drag").find("li").first().clone(true, true).appendTo($("#people-drag").find("ul"));
			$("#people-drag").find("li").first().remove();
			$("#people-drag").css("margin-left", (parseInt($("#people-drag").css("margin-left"))+166)+"px" );
		}
	}
	if(navigator.platform.indexOf("iPad")>=0 || jQuery.browser.mobile){
		var preInterval=window.setInterval(function(){
			$("#people-drag").css("left", parseInt($("#people-drag").css("left"))-1+"px");
			checkOffScreen();
		}, 25);
		$("#people-drag").dragThrow({
			axis: "x",
			ticks: 25,
			dragging: function(){
				checkOffScreen();
				if(preInterval !== undefined){
					clearInterval(preInterval);
				}
			},
			throwing: checkOffScreen,
			clicker: function(){
			}
		});
	}else{
		
		var speed = 0;
		var over = false;
		
		var intval=window.setInterval(function(){
			$("#people-drag").css("left", parseInt($("#people-drag").css("left"))+speed+"px");
			checkOffScreen();
			if(over == false && (speed < 0 || speed > 0)){
				speed *= 0.95;
				if(Math.floor(speed) == 1 || Math.floor(speed) == -1){
					speed = 0;	
				}
			}
		}, 15);
		
		$("#people-drag").mousemove(function(e){
			speed = -((e.clientX-$(document).width()/2)/60);
			over = true;
		});
		
		$("#people-drag").mouseleave(function(){
			over = false;
		});
	}
		checkOffScreen();
}

function fadeEl(){
	$('.homeCallouts li, .ddCallouts > li, #mainNav a, #leftNav a, .careersList a, .back, .quoname, .formDown .formTitle, .formDown .arrowBtn, .leftArrow a, .rightArrow a, .blogArchive strong, .blogInfo span a, .tagCloud li a, .blogShare a, .tweet .tweet-author, .tweet .tag, #tabs a').not('#mainNav .home a,  #mainNav a.parent, #leftNav .on a, #footerLeft span.links').fadeTo(0,0.65);
	
	$('#footerLeft span.links a, #footerLeft span.links span, #footerLinks a, #footerArrow').fadeTo(0,0.35);
	
	$('#mainNav a, .careersList a, .back, .homeCallouts li, .leftArrow a, .rightArrow a, .blogArchive strong, .blogInfo span a, .tagCloud li a, .blogShare a, #tabs a').not('#mainNav .home a, #mainNav a.on, #mainNav a.parent, .leftNav .on').hover(function(){
		$(this).stop().fadeTo(100,1);
	},function(){
		$(this).stop().fadeTo(500,0.65);
	});
	
	$('#leftNav li').not('#leftNav .on').css('background-position','-140px 0').hover(function(){
		$(this).find('a').stop().fadeTo(100,1);
		$(this).stop().animate({
			backgroundPosition:'0 0'
		}, 500);
	},function(){
		$(this).find('a').stop().fadeTo(500,0.65);
		$(this).stop().animate({
			backgroundPosition:'-140px 0'
		}, 500);
	});
	
	$('#footerLeft span.links a, #footerLinks a[href], #footerArrow').hover(function(){
		$(this).stop().fadeTo(100,1);
	},function(){
		$(this).stop().fadeTo(500,0.35);
	});
}

function workCallouts(){
	$(".fadeCallouts.caseStudies a").hover(function(){
		$("img", this).stop().fadeTo(200, 0);
	},function(){
		$("img", this).stop().fadeTo(300, 1);
	});
	$(".fadeCallouts a").not($(".fadeCallouts.caseStudies a")).fadeTo(0, 0.65);
	$(".fadeCallouts a").not($(".fadeCallouts.caseStudies a")).hover(function(){
		$(this).stop().fadeTo(100, 1);
	},function(){
		$(this).stop().fadeTo(500, 0.65);
	});
	
	//Awards
	
	/*$(".fadeCallouts li").each(function(){
		if($("span", this).find("img").length == 0){
			var before = $("span", this).height();
			$("span", this).css("height", "auto");
			var auto = $("span", this).height();
			//15px needs to be sorted out;
			var calc = (auto / 15)
			$("span", this).css("line-height", before / calc+"px");
			$("span", this).css("height", before);
		}
	});*/
	var Þ = $("#rightColumn .rightArrow");
	if(Þ.html() == ""){
		Þ.hide();
	}
}

function ddCallouts(){
	$('.ddCallouts ul').hide();
	$(".ddCallouts").css("height", Math.max(findHeight($(".ddCallouts>li")))+"px");
	$('.ddCallouts > li').hover(function(){
		var ddHeight =  $(this).find('ul').height() + $(this).find('h3').height() + 10;
		$(this).addClass('over').stop().fadeTo(100,1);
		$(this).find('div').stop().animate({
			height:ddHeight
		},300,'easeOutQuint');
		
		$(this).find('ul').show();
	},function(){
		$(this).removeClass('over').stop().fadeTo(500,0.65);
		$(this).find('ul').hide();
		$(this).find('div').stop().animate({
			height:60
		},500,'easeOutQuint');
		
		/*$(".ddCallouts").stop().animate({
			height:100
		},300,'easeOutQuint');*/
		
	});
	
	$(".homeCallouts li").each(function(){
		if($(this).find("p").length !== 0){
			$(this).css({height: "20px"});
		}else{
			$(this).find("a").css("background", "url(/static/images/arrow.png) 100% 4px no-repeat");
			$(this).find("a").css("height", "60px");
		}
	});
	$(".homeCallouts li").hover(function(){
		if($(this).find("p").length !== 0){
			var hcHeight = $(this).find("p").height() + 25;
			$(this).stop().animate({
				height: hcHeight,
				opacity: 1
			}, 300);
		}
	},function(){
		if($(this).find("p").length !== 0){
			$(this).stop().animate({
				height: "20px",
				opacity: 0.65
			}, 500);
		}
	});
	$('.homeCallouts li').click(function(){
		var url = $(this).find('a:first').attr('href');
		document.location.href = url;
		return false;
	});
}
function footer(){
	var paddingBottom = $("#people-thumb").length == 0 ? 100: 275;
	$("#content").css("padding", "0 0 "+paddingBottom+"px 0");
	window.footerHeight = $('#footerLinksWrap').height();
	window.bottomPadding = parseInt($('#content').css('padding-bottom'));
	$('#footerLinksWrap').hide();
	$('#footerArrow').toggle(function(){
		var scrollDist = $("html").scrollTop();
		$(this).addClass('up');
		if($('body').scrollTop() > scrollDist){
			scrollDist = $('body').scrollTop();
		}
		$('#footerLinksWrap').slideDown(1000, 'easeOutQuint');
		$('#content').stop().animate({
			paddingBottom:footerHeight + bottomPadding
		}, 1000, "easeOutQuint");
		$('html,body').stop().animate({
			scrollTop:scrollDist + footerHeight
		},600, "easeOutQuint");
	},function(){
		$(this).removeClass('up');
		$('#footerLinksWrap').slideUp(1000, 'easeOutQuint');
		$('#content').stop().animate({
			paddingBottom:bottomPadding
		}, 1000, "easeOutQuint");
	});
}
function showSite(){
	if(!$('#background').hasClass('video')){
		$('#overlay').stop().fadeTo(1000,opacity,'easeOutRegular');
	}
	//Custom Listener for when the page is tweened into existance:
	$(document).trigger("tweenReady");
}

calloutArray=[];

//Caption, flv location, static image location, opacity

calloutArray.push(['<h3><a href="/casestudies/ec-harris">EC Harris</a></h3><p>Wickedweb deliver career intranet application for EC Harris to drive employee engagement.<br/><a href="/casestudies/ec-harris">Explore case study</a></p>', "/static/flash/dubai.flv", "/media/43/2643-dubai.jpg", .6]);
calloutArray.push(['<h3><a href="/casestudies/wagamama-art-and-eat-campaign/">wagamama</a></h3><p>Wickedweb roll out integrated digital marketing campaign for wagamama<br/><a href="/casestudies/wagamama-art-and-eat-campaign/">Explore case study</a></p>', "/static/flash/wagamama.flv", "/media/09/2509-artandeatbg.jpg", .3]);	
calloutArray.push(['<h3><a href="/casestudies/range-rover/">Range Rover</a></h3><p>Wickedweb deliver Range Rover campaign microsite in partnership with The Telegraph<br/><a href="/casestudies/range-rover/">Explore case study</a></p>', "/static/flash/range_rover.flv", "/media/49/2549-range-rover_background.jpg", .3]);
calloutArray.push(['<h3><a href="/casestudies/mitre/">Mitre</a></h3><p>Wickedweb deliver global web design and build solution for Mitre<br><a href="/casestudies/mitre/">Explore case study</a></p>', "/static/flash/mitre.flv", "/static/images/mitre_home.jpg", .4]);

function createCookie(name,value,days){
	var expires = '';
	if(days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = '; expires='+date.toGMTString();
	}
	document.cookie = name + '=' + value + expires + '; path=/';
}
function readCookie(name){
	var retVal = null;
	var ca = document.cookie.replace(/; /g,';').split(';');
	for(var i=0; i<ca.length; i++){
		var c = ca[i].split('=');
		if(c[0] == name){
			retVal = c[1];
			break;
		}
	}
	return retVal;
}

flashvars = {};
for(i=0; i<calloutArray.length; i++){
	flashvars["video" + i] = calloutArray[i][1];
}

var curCallout = 0;

function changeCallout(n){
	$('#frames li').removeClass('on');
	$('#frames li:eq(' + n + ')').addClass('on');
	$('#homeRight').stop().animate({
		height:'4px',
		marginBottom:'148px'
	},500, 'easeOutRegular',function(){
		$('#homeRightInner').html(calloutArray[n][0]);
		$('#homeRight').animate({
			//height: $('#homeRightInner').outerHeight()
			height: '122px',
			marginBottom: '30px'
		},500, 'easeOutRegular');
	});
	if((!$.flash.available || jQuery.browser.mobile)){
		opacity = calloutArray[n][3];
		$("#overlay").stop().fadeTo(500, 1, function(){
			var imgSrc = calloutArray[n][2];
			preload(imgSrc, function(){
				
				if(navigator.platform.indexOf("iPad")>=0 || jQuery.browser.mobile){
					$("#background").css("background-image", "url("+imgSrc+")");
				}
				else{
					$("#background img").attr("src", imgSrc);
				}
				window.setTimeout(function(){
					$("#overlay").stop().fadeTo(500, opacity);
				}, 10);
			})
		});
	}
}


function iosCalloutChange(){
	if(curCallout<calloutArray.length-1){
		changeCallout(++curCallout);
	}else{
		curCallout = 0;
		changeCallout(curCallout);
	}
}

function preload(url, funct){
	var img = eval["img" + url.slice(url.lastIndexOf("/") + 1, url.lastIndexOf("."))];
	img = new Image();
	img.onload = funct;
	img.src = url;
}

function initSite(){
	if(animated == 'yes' && $('#background img').size() > 0){
		if($('#contactBox').size() > 0){
			$('#background').css('background-image', 'url(' + $('#background img:first').attr('src') + ')');
		}
		if($('#background').hasClass('video')){
			if($.flash.available && !jQuery.browser.mobile){
				$("#overlay").stop().fadeTo(0,0);
				$('#top').append('<div id="vidControls" class="notouch"><div id="volume" title="Sound Off"></div><ul id="frames"></ul><div id="play" title="Pause"></div></div>');
				flashvars.sound = readCookie('sound');
				if(flashvars.sound == 'soundoff'){
					$('#volume').addClass('mute').attr('title', 'Sound On');
				}
				$('#background').flash({swf:'/static/flash/background_with_controls.swf', width:'100%', height:'100%', wmode:'transparent', flashvars:flashvars});
			}else{
				$('#top').append('<div id="vidControls" class="notouch"><ul id="frames"></ul><div id="play" title="Pause"></div></div>');
				changeCallout(0);
				window.cycleInt = setInterval("iosCalloutChange()", 7000);
				if(jQuery.browser.mobile){
					$('#vidControls').removeClass('notouch');
				}
			}
			if(calloutArray.length > 1){
				for(i=0; i<calloutArray.length; i++){
					flashvars["video" + i] = calloutArray[i][1];
					var name = calloutArray[i][0].slice(calloutArray[i][0].indexOf('">') + 2, calloutArray[i][0].indexOf('</a>'));
					$('#frames').append('<li value="' + i + '" title="' + name + '"></li>');
				}
				$('#frames li:first').addClass('on');
				$('#frames li').click(function(){
					if(!$(this).hasClass('on')){
						$('#play').removeClass('pause').attr('title', 'Pause');
						$('#frames li').removeClass('on');
						$(this).addClass('on');
						var val = $(this).attr('value');
						if($.flash.available){
							$('#background').find('object').flash(function(){
								this.SetVariable('resetvar',val);
							});
						}
						else{
							curCallout = val;
							clearInterval(cycleInt);
							window.cycleInt = setInterval("iosCalloutChange()", 7000);
							changeCallout(val);
						}
					}
				});
			}
			$('#play').click(function(){
				var val = 'pause';
				if($(this).hasClass('pause')){
					$(this).removeClass('pause').attr('title', 'Pause');
					val = 'play';
					if(!$.flash.available){
						iosCalloutChange();
						window.cycleInt = setInterval("iosCalloutChange()", 7000);
					}
				}
				else{
					$(this).addClass('pause').attr('title', 'Play');
					if(!$.flash.available){
						clearInterval(cycleInt);
					}
				}
				if($.flash.available){
					$('#background').find('object').flash(function(){
						this.SetVariable('resetvar',val);
					});
				}
			});
			$('#volume').click(function(){
				var val = 'soundoff';
				if($(this).hasClass('mute')){
					$(this).removeClass('mute').attr('title', 'Sound Off');
					val = 'soundon';
					createCookie('sound','soundon',365);
				}
				else{
					$(this).addClass('mute').attr('title', 'Sound On');
					createCookie('sound','soundoff',365);
				}
				$('#background').find('object').flash(function(){
					this.SetVariable('resetvar',val);
				});
			});
			showSite();
		}else{
			var imgSrc = $('#background img:first').attr('src');
			preload(imgSrc, function(){
				window.setTimeout(function(){
					showSite();
				}, 10);
			});
		}
	}else{
		$('#overlay').stop().fadeTo(0,opacity);
	}
	
}
function findHeight($this){
	var height = 0;
	$this.find('> *').each(function(){
		height += $(this).outerHeight();
	});
	return height;
}
function formDown(){
	$('.formDown').addClass('formDownjs');
	$('.formDownInner input[type="file"]').each(function(){
		$(this).val(null);
		$(this).addClass('file');
		$(this).fadeTo(0,0);
		$('<span class="fauxFile">Attach CV</span>').insertAfter($(this));
		$(this).change(function(){
			var loc = $(this).val().split('\\');
			var fileName = loc[loc.length-1];
			$(this).parent().find('.fauxFile').text(fileName);
		});
	});
	$('.formDownInner select').each(function(){
		var val = $(this).find(':selected').text();
		if(val.length > 23){
			val = val.slice(0,19);
			if(val.lastIndexOf(' ') == val.length - 1){
				val = val.slice(0,18);
			}
			val += '...';
		}
		$(this).fadeTo(0,0);
		$('<span class="fauxSelect">' + val + '</span>').insertAfter($(this));
		$(this).parent().find('.fauxSelect').text(val);
		$(this).change(function(){
			var val = $(this).find(':selected').text();
			if(val.length > 23){
				val = val.slice(0,19);
				if(val.lastIndexOf(' ') == val.length - 1){
					val = val.slice(0,18);
				}
				val += '...';
			}
			$(this).parent().find('.fauxSelect').text(val);
		});
		$(this).keyup(function(event){
			var val = $(this).find(':selected').text();
			if(val.length > 23){
				val = val.slice(0,19);
				if(val.lastIndexOf(' ') == val.length - 1){
					val = val.slice(0,18);
				}
				val += '...';
			}
			$(this).parent().find('.fauxSelect').text(val);
		});
	})
	$('.formDownInner').each(function(){
		$(this).height(24).find('.formTitle, .arrowBtn').click(function(){
			$this = $(this).parent();
			$('.formDownInner').not($this).removeClass('open').css('z-index', 10).stop().animate({
				height:24
			},700,'easeOutQuint');
			if(!$this.hasClass('open')){
				$this.addClass('open').css('z-index', 100).stop().animate({
					height:(findHeight($this) - 24)
				},700,'easeOutQuint',function(){
					$this.css('height','auto');
				});
			}
			else{
				$this.removeClass('open').stop().animate({
					height:24
				},700,'easeOutQuint',function(){
					$this.css('z-index', 10);
				});
			}
		});
	});
	$('input, textarea').focus(function(){
		var def = $(this).attr('title');
		var val = $(this).val();
		if(val == def){
			$(this).val('');
		}
	});
	$('input, textarea').blur(function(){
		var def = $(this).attr('title');
		var val = $(this).val();
		if(val.length == 0 && typeof(def) !== 'undefined' && def !== false && def.length > 0){
			$(this).val(def);
		}
	});
	$('input, textarea').each(function(){
		var def = $(this).attr('title');
		var val = $(this).val();
		if(val != def && typeof(def) !== 'undefined' && def !== false && def.length > 0){
			$(this).val(def);
		}
	});
	$('.formDown').hover(function(){
		$(this).find('.formTitle, .arrowBtn').not('.open .formTitle, .open .arrowBtn').stop().fadeTo(100,1);
	},function(){
		$(this).find('.formTitle, .arrowBtn').not('.open .formTitle, .open .arrowBtn').stop().fadeTo(500,0.65);
	});
}
function blogArchive(){
	$('.blogArchive .year > strong').click(function(){
		$('.blogArchive .year > ul:visible').stop().slideUp('easeInOutQuint', function(){
			$(this).css('height', 'auto');
		});
		$(this).parent().find('ul:hidden').stop().slideDown('easeInOutQuint', function(){
			$(this).css('height', 'auto');
		});
	})
}
var mouseDown = false;
var currentX = 0
var startX = 0;
var sX = 0
var eX = 0;
var newPos = 0;
var d = new Date();
var t1 = 0;
var t2 = 0;
function showCasePos(){
	var sWidth = $(window).width();
	var remainder = (sWidth / 2) - (652 / 2) - 652;
	var xOffset = $('#wideColumn').offset().left - remainder;
	if(sWidth < 960){
		sWidth = 960;
	}
	$('#showcase').css('margin-left', -xOffset).width(sWidth - $('#showcase').offset().left);
}
function showcasePos(n){
	$('title').text(Math.abs((n - (652 - Math.abs(newPos)))))
	$('#showcase ul').animate({
		marginLeft: n
	}, Math.abs((n - (652 - Math.abs(newPos)))), "swing");
}
function showcaseDrag(){
	$('#showcase').mousedown(function(e){
		$('#showcase ul').stop();
		mouseDown = true;
		d = new Date();
		t1 = d.getTime();
		startX = e.pageX;
		sX = e.pageX;
		currentX = $('#showcase ul').offset().left;
		//d = new Date();
		//t1 = d.getTime();
		return false;
	});
	$(document).mouseup(function(e){
		if(mouseDown){
			mouseDown = false;
			eX = e.pageX;
			var maxSpeed = 20;
			var deltaX = (eX - sX);
			var deltaMS = Math.max((t2 - t1),1);
			var speedX = Math.max(Math.min((deltaX / deltaMS), maxSpeed ), -maxSpeed);
			var lastStepTime = new Date();			
			$('#showcase ul').css( "text-indent", 100 );
			$('#showcase ul').stop().animate({
				textIndent: 0
			},{
				duration:(Math.abs(speedX) * 120),
				step: function(currentStep){
					speedX *= (currentStep / 100);
					var now = new Date();
					var stepDuration = (now.getTime() - lastStepTime.getTime());
					lastStepTime = now;
					var position = $('#showcase ul').offset().left - $('#showcase').offset().left
					var newPos = (position + (speedX * stepDuration));
					if(newPos < 0){
						var a = Math.floor(-newPos/652);
						newPos += (a * 652);
						$('#showcase li:lt(' + a + ')').appendTo($('#showcase ul'));
					}
					else{
						var a = Math.floor(newPos/652) + 1;
						var n = (($('#showcase li').size() - 1) - a);
						newPos -= (a * 652);
						$('#showcase li:gt(' + n + ')').prependTo($('#showcase ul'));
					}
					$('#showcase ul').css('margin-left', newPos);
				},
				complete:function(){
					newPos1 = 652 * Math.round(($('#showcase ul').offset().left - $('#showcase').offset().left) / 652);
					showcasePos(newPos1);
				}
			});
			return false;
		}
	});
	$(document).mousemove(function(e){
		if(mouseDown){
			d = new Date();
			t2 = d.getTime();
			$('#showcase ul').stop();
			newPos = (e.pageX - startX) + currentX - $('#showcase').offset().left;
			//showcaseFade();
			if(e.pageX < startX){
				var a = Math.floor(-newPos/652);
				newPos += (a * 652);
				$('#showcase ul').css('margin-left', newPos);
				$('#showcase li:lt(' + a + ')').appendTo($('#showcase ul'));
			}
			else if(e.pageX > startX){
				var a = Math.floor(newPos/652) + 1;
				var n = (($('#showcase li').size() - 1) - a);
				newPos -= (a * 652);
				$('#showcase ul').css('margin-left', newPos);
				$('#showcase li:gt(' + n + ')').prependTo($('#showcase ul'));
			}
			startX = e.pageX;
			currentX = $('#showcase ul').offset().left;
			return false;
		}
	});
}
function showcaseFade(){
	var midPoint = (($(window).width() - 652) / 2);
	$('#showcase img').each(function(){
		if($(this).offset().left > -652 && $(this).offset().left < $(window).width()){
			var fade = 1 - Math.abs(midPoint - $(this).offset().left) / 2000;
			if(fade < 0.65){
				fade = 0.65;
			}
			$(this).fadeTo(0,fade);
		}
	});
}
function showcaseInit(){
	if($('#showcase').size() > 0){
		$('#showcase ul').width($('#showcase li').size() * 652);
		showCasePos();
		showcaseDrag();
		//showcaseFade();
		$(window).resize(function(){
			showCasePos();
		});
	}
}
function mobileHandler(){
	if(navigator.platform.indexOf("iPad")>=0 || jQuery.browser.mobile){
		$('#background').flash().remove();
		$('#background').css('background-image', 'url('+$('#background img').attr('src')+')');
		//$("#background img").remove();
		$('#background, #overlay').css("height", $("#wrap").height()+"px").css("width", $("#wrap").width()+"px");
		$(window).resize(function() {
			$('#background, #overlay').css("height", $("#wrap").height()+"px").css("width", $("#wrap").width()+"px");
		});
	}
}

var tabdata = {};
function tabs(tar){
	$(">div", tar).height(37).css("overflow", "hidden").last();
	$(">div", tar).first().css("height", "auto").addClass("selected").find("h3").css("background", "url(/static/images/arrows.png) no-repeat 470px -18px");
	
	$("h3", tar).click(function(){
		if(!$(this).parent().hasClass("selected")){
			$(".selected", tar).animate({
				height:37
			}, 500);
			
			$(this).parent().animate({
				height: findHeight($(this).parent())+7+20
			}, 500);
			
			$(".selected", tar).removeClass("selected").find("h3").css("background", "url(/static/images/arrows.png) no-repeat 470px 6px");
			
			$(this).css("background", "url(/static/images/arrows.png) no-repeat 470px -18px")
			$(this).parent().addClass("selected");
		}
	});
	
}

function solutionsLogic(){
	//Depends on dropdown();
	
	if($("#rightColumn .blackBox").length !== 0 && $("#leftNav .clicked ul>li").length !== 0){
		$("#mod_signup_service").empty();
		$("#mod_signup_service").append('<option value="notselected">Desired service</option>');
	
		for(var g=0;g<$("#leftNav .clicked ul>li").length;g++){
			var val = $("#leftNav .clicked ul>li").eq(g).find("a").text();
			
			while (val.indexOf(" ") !== -1){
				val = val.replace(" ", "");	
			}
			
			$("#mod_signup_service").append('<option value="'+val+'">'+$("#leftNav .clicked ul>li").eq(g).find("a").text()+'</option>');
		}
		
		var target = $("#leftNav .on").hasClass("sub3") ? $("#leftNav .on") : $("#leftNav .on").parent().find("li.parent");
		
		var tar = target.find("a").first().text();
			
		while(tar.indexOf(" ") !== -1){
			tar = tar.replace(" ", "");	
		}
		
		$("#mod_signup_service").val(tar);
		$(".fauxSelect").empty().append(target.find("a").first().text());
		
		if($.trim($("#rightColumn .blackBox").text()) == "%%content:blackbox%%" || $.trim($("#rightColumn .blackBox").text()) == ""){
			$("#rightColumn .blackBox").empty().append('Contact us to find out more about our '+target.find("a").first().text()+' service');
		}
	}
}

function hotfix(){
	
	$("head").append('<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE" />');
	
	if($(".thankyou").length !== 0){
		$(".thankyou").each(function(){
			$(this).parents(".formDownInner").find(".arrowBtn").click();
		});
	}
}

function homepageTabs(){
	var resetSize = 47;
	var tar = [];
	var tarId = -1;
	var toBeAdded = [];
	var goingUp = false;
	var addToQueue = function(){};
	var nextAction = "down";
	var tweenTime = 300;
	
	$("#content").height(785);
	
	$("#homeSlideContainer").height(resetSize);
	
	$(".ddCalloutsHome li").mouseenter(function(e){
		
		if(tar !== [] && $(".selected").parent().index() !== $(this).index()){
			$("#homeSlideContainer").trigger("mouseleave");	
		}
		tar = $(this);
		tarId = $(this).index();
		
		if(goingUp){
			addToQueue = function(){
				$(".ddCalloutsHome li").eq(tarId).find("div").addClass("selected");
				$(".ddCalloutsHome li").eq(tarId).stop().fadeTo(tweenTime, 1);
				$("#homeTabsContent").stop().fadeTo(tweenTime, 1);
				$("#homeTabsContent").find(">div").hide();
				$("#homeTabsContent").find(">div").eq(tarId).show();
				$("#homeSlideContainer").animate({
					height: $("#homeTabsContent").find(">div").eq(tarId).height()+60+20
				}, tweenTime);
			};	
		}else{
			tar.find("div").addClass("selected");
			tar.stop().fadeTo(tweenTime, 1);
			$("#homeTabsContent").stop().fadeTo(tweenTime, 1);
			$("#homeSlideContainer").animate({
				height: $("#homeTabsContent").find(">div").eq(tar.index()).height()+60+20
			}, tweenTime);
		}
		
		e.preventDefault();
		return false;
	});
	$("#homeSlideContainer").mouseleave(function(e){
		goingUp = true;
		tar = [];
		$(".selected").parent().fadeTo(tweenTime, .65);
		$("#homeTabsContent").stop().fadeTo(tweenTime, .65);
		$("#homeSlideContainer").stop(true).animate({
			height: resetSize
		}, tweenTime, function(){
			$(".selected").removeClass("selected");
			goingUp = false;
			addToQueue();
			addToQueue = function(){};
		});
		e.preventDefault();
		return false;
	});
	
	$(".ddCalloutsHome li").click(function(){
		return false;
	});
	
}



$(function(){
	$.dev = window.location.hash=="#dev";
	
	fadeEl();
	initSite();
	formDown();

	if(window.location.pathname !== "/dev/"){
		ddCallouts();
	}else{
		homepageTabs();
	}
	
	blogArchive();
	footer();
	showcaseInit();
	
	imageSliderPeople();
	dropdown("#leftNav");
	tabs("#tabs");
	workCallouts();
	mobileHandler();
	solutionsLogic();
	
	hotfix();
});

$(window).unload(function(){});
