
///////////////////////////
// Generate custom fonts
function loadFonts() {
	
	$('ul.navigationItems li').hide()
	Cufon.replace('ul.navigationItems li', {
		hover: true
	});
Cufon.replace('.helvetica', {
		ignore: { span: true }
	});
	Cufon.now();
	$('ul.navigationItems li').show()
	mapNav();

	/*
	var myfont = { src: 'fonts/helvetica.swf' };
	sIFR.activate(myfont);


	sIFR.replace(myfont, { selector: 'h1', css: {'.sIFR-root': { 'color': '#000000', 'letter-spacing' : '0' }, 'strong': { 'color': '#353535'} , 'sup': { 'font-weight': 'bold'}},wmode: 'transparent'});
	*/

	$('.homeHeadlineHeading').mouseenter(function(){
		
		if ( $(this).children('a').children('h1').hasClass('helvetica_active') ) {
			return false;
		} else {
			$(this).children('a').children('h1').addClass('helvetica_active');
			Cufon.refresh();
		}
		
		
	}).mouseleave(function(){
		$(this).children('a').children('h1').removeClass('helvetica_active')
		Cufon.refresh();
	});

    $('ul.cultureBlogFeeds li a').mouseenter(function () {

        if ($(this).children('h2').hasClass('helvetica_active')) {
            return false;
        } else {
            $(this).children('h2').addClass('helvetica_active');
            Cufon.refresh();
        }


    }).mouseleave(function () {
        $(this).children('h2').removeClass('helvetica_active')
        Cufon.refresh();
    });		
	

}


///////////////////////////
// Map navigation

function restoredefault() {

    //find active position and width
    var contentOffset = $('.navigationItems').offset();
    var navActive = $('ul.navigationItems li.active').position();
    var navActiveWidth = $('ul.navigationItems li.active').width() / 2;
    var navActivePosition = contentOffset.left - 1280 + navActive.left + navActiveWidth;

    if ($('ul.navigationItems li.active').hasClass('blog')) {

    } else {
        $('.socialEblogger').removeClass('socialEbloggerActive')
    }

    $('#navigationBottom').stop(true, true).animate({
        left: navActivePosition
    }, 500, function () {
    });
}


function bindSubnavigationChildMenu() {
    $('.subnavigationContainer, #blogLanding').mouseleave(function () {
        $('#blogSubnavigationList li').each(function () {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active')
            }
        })
        t = setTimeout("restoredefaultSubNav()", 1000);
    });

}


function restoredefaultSubNav() {



    var navActive = $('#blogSubnavigationList li a.active').position();
    var subNavPosition = $('#blogSubnavigationList li a.active').position();
    var subNavWidth = $('#blogSubnavigationList li a.active').width() / 2;
    var subNavActivePosition = (subNavPosition.left + subNavWidth) - 8

    if ($('#blogSubnavigationList li').hasClass('active')) {
        bindSubnavigationChildMenu()
    } else {

        $('.subNavIndicator').stop(true, true).animate({
            left: subNavActivePosition
        }, 500, function () {
            if ($('#blogSubnavigationList li a.active').siblings('ul').size() > 0) {
            } else {
                $('.subnavigationContainer').css('border-top', 'none').children('#blogsubnavContentContainer').empty().parent().slideUp()
            }
        });
    }


}

function returnToActive() {

    var cloneContent = $('#blogSubnavigationList li a.active').siblings('ul').children('li').children().clone();
    $('#blogSubnavigationList li a.active').parent().addClass('active');
    $('.subnavigationContainer').css('border-top', '1px solid #d9d9d9').children('#blogsubnavContentContainer').empty().append(cloneContent).parent().slideDown();
    var navPosition = $('#blogSubnavigationList li a.active').position();
    var navWidth = $('#blogSubnavigationList li a.active').width() / 2;


    var moveTo = (navPosition.left + navWidth) - 8

    $('.subNavIndicator').stop(true, false).animate({
        left: moveTo
    }, 500, function () {
    });
}


function mapNav() {

    //find active position and width
    var t;
    var contentOffset = $('.navigationItems').offset();
    var navActive = $('ul.navigationItems li.active').position();

    var navActiveWidth = $('ul.navigationItems li.active').width() / 2;
    var navActivePosition = contentOffset.left - 1280 + navActive.left + navActiveWidth

    if ($('ul.navigationItems li.active').hasClass('blog')) {
        $('.socialEblogger').addClass('socialEbloggerActive')
    } else {
        $('.socialEblogger').removeClass('socialEbloggerActive')
    }



    //place active
    $('#navigationBottom').css('left', navActivePosition).css('background-color', 'transparent')

    //remember active
    var currentSelected = $('.navigationItems li.active').children().attr('name');


    $('.navigationItems li').mouseenter(function () {
        clearTimeout(t);
        var navPosition = $(this).position();
        var navWidth = $(this).width() / 2;

        if ($(this).hasClass('blog')) {
            $('.socialEblogger').addClass('socialEbloggerActive')
        }

        var moveTo = contentOffset.left - 1280 + navPosition.left + navWidth;
        $('#navigationBottom').stop(true, false).animate({
            left: moveTo
        }, 500, function () {
        });
    }).mouseleave(function () {
        t = setTimeout("restoredefault()", 1000);
    });


    //place blogActive active



    /*
    var subNavPosition = $('#blogNavigation p a.active').position();
    var subNavWidth = $('#blogNavigation p a.active').width()/2;
    var subNavActivePosition = (subNavPosition.left+subNavWidth)-8
    $('.subNavIndicator').css('left',subNavActivePosition).css('background-color','transparent')	
    */





    if ($('#blogSubnavigationList li a.active').siblings().size() > 0) {
        returnToActive()
    }




    $('#blogSubnavigationList li a').mouseenter(function () {

        if ($(this).siblings().size() > 0) {
            var cloneContent = $(this).siblings('ul').children('li').children().clone();
            $(this).parent().siblings().removeClass('active')
            $(this).parent().addClass('active')
            //$(this).siblings('.blogSubNavHidden').show()
            //$('.subnavigationContainer').css('border-top','1px solid #d9d9d9').children('#blogsubnavContentContainer').empty().append(cloneContent).parent().slideDown();	
            $('.subnavigationContainer').css('border-top', '1px solid #d9d9d9').children('#blogsubnavContentContainer').empty().append(cloneContent).parent().slideDown();
        } else {

            if ($('#blogSubnavigationList li a.active').siblings().size() > 0) {
                //returnToActive()
                //return false;
                $('.subnavigationContainer').css('border-top', 'none').children('#blogsubnavContentContainer').empty().parent().slideUp()
            } else {
                $('.subnavigationContainer').css('border-top', 'none').children('#blogsubnavContentContainer').empty().parent().slideUp()
            }


        }



        clearTimeout(t);
        var navPosition = $(this).position();
        var navWidth = $(this).width() / 2;


        var moveTo = (navPosition.left + navWidth) - 8

        $('.subNavIndicator').stop(true, false).animate({
            left: moveTo
        }, 500, function () {
        });

    }).mouseleave(function () {
        if ($('#blogSubnavigationList li a.active').siblings().size() > 0) {
            t = setTimeout("returnToActive()", 1000);
        } else {
            t = setTimeout("restoredefaultSubNav()", 1000);
        }

    });




    $('.onOurMinds li .socialIcon').mouseenter(function () {
        $(this).siblings('p').children('a').addClass('col_coal')
    }).mouseleave(function () {
        $(this).siblings('p').children('a').removeClass('col_coal')
    });

    $('.contactDetailsSocial').mouseenter(function () {
        $(this).siblings('.socialIcon').trigger('hover');
    }).mouseleave(function () {
        $(this).siblings('p').removeClass('col_coal')
    });

    var socialIconHover;
    var socialIconHoverActive;

    $('.onOurMinds li p a').mouseenter(function () {

        if ($(this).parent().siblings().hasClass('socialIcon')) {
            socialIconHover = $(this).parent().siblings('.socialIcon').attr('class').split(" ")[1]
            socialIconHoverActive = socialIconHover + 'Active'
            $(this).parent().siblings('.socialIcon').addClass(socialIconHoverActive)
        } else {

        }


    }).mouseleave(function () {

        if ($(this).parent().siblings().hasClass('socialIcon')) {

            $(this).parent().siblings('.socialIcon').removeClass(socialIconHoverActive)
        }
    });



}



///////////////////////////
// Get twitter data
function twitterFeeds(username,count) {
	
	// Define JSON
	var fetchTimeLine = 'http://api.twitter.com/1/statuses/user_timeline/'+username+'.json?count='+count+'&include_rts=1&callback=?'
	
	// Get JSON
	jQuery.getJSON(fetchTimeLine,{
		},function(tweets) {

		  // Handle response here
		  var statusHTML = [];
		  
		  //update followers
		  var followersCount = tweets[0].user.followers_count+' followers';
		  var headingWidth = $('#twitterFollowerCount').siblings('h1').children('strong').width();
		  $('#twitterFollowerCount').css('width',headingWidth+'px').empty().append(followersCount)
		  
		  for (var i=0; i<tweets.length; i++){ 
			if ( i == (count-1) ) {
				var noBorder = 'class="last"'
				//caught
			}  else {
				var noBorder = '';
			} 
			  
		    var username = tweets[i].user.screen_name;
		    var tweetId = tweets[i].id_str;
		    
		    var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
		      return '<a target="_blank" class="twitter" href="'+url+'">'+url+'</a>';
		    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
		      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
		    });
		    var statusLength = status.length 
		    if ( statusLength > 240 ) {
		    	status = status.slice(0,240)
		  		var closeCorrectly = "..."
		    } else {
		    	var closeCorrectly = "<br/>"
		    }
		 statusHTML.push('<li ' + noBorder + '><p>' + status + closeCorrectly + '</p><a href="http://twitter.com/' + username + '/statuses/' + tweetId + '">' + relative_time(tweets[i].created_at) + '</a>&#183;<a target="_blank" href="https://twitter.com/intent/tweet?in_reply_to=' + tweetId + '">Reply</a>&#183;<a target="_blank" href="https://twitter.com/intent/retweet?tweet_id=' + tweetId + '">Retweet</a>&#183;<a target="_blank" href="https://twitter.com/intent/favorite?tweet_id=' + tweetId + '">Favorite</a></li>');
		  }
		  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
	});

	function relative_time(time_value) {
		  var values = time_value.split(" ");
		  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
		  var parsed_date = Date.parse(time_value);
		  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
		  delta = delta + (relative_to.getTimezoneOffset() * 60);
	
		  if (delta < 60) {
		    return 'less than a minute ago';
		  } else if(delta < 120) {
		    return 'about a minute ago';
		  } else if(delta < (60*60)) {
		    return (parseInt(delta / 60)).toString() + ' minutes ago';
		  } else if(delta < (120*60)) {
		    return 'about an hour ago';
		  } else if(delta < (24*60*60)) {
		    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
		  } else if(delta < (48*60*60)) {
		    return '1 day ago';
		  } else {
		    return (parseInt(delta / 86400)).toString() + ' days ago';
		  }
	}	
	
}

function applyDivHovers(element,click) {
	
	//hovers
	$('.'+element).mouseenter(function(){
		
		if ( $(this).hasClass(element+'Active') ) {
			return false;
		} else {
			$(this).addClass(element+'Hover');
			if ( element === "homeSnippet" ) {
				$(this).append('<div class="goButton iconSet"></div>')
			}
			Cufon.refresh();
		}
		
		
	}).mouseleave(function(){
		$(this).removeClass(element+'Hover');
		if ( element === "homeSnippet" ) {
			$(this).children('div.goButton').empty().remove()
		}
		Cufon.refresh();
	});	
	
	//active
	$('.'+element).mousedown(function(){
	    $(this).addClass(element+'Clicked');
	    Cufon.refresh();
	}).mouseup(function(){
	    $(this).removeClass(element+'Clicked');
	    
	});		
	
	//click
	//active
	$('.' + element).click(function (triggered) {

	    if (click === "click") {
	        var elementLink = $(this).children('a').attr('href');
	        if (elementLink === "#" || elementLink === "") {

	        } else {
	            var target = $(this).children('a').attr('target');
	            if (target === "_blank" || target === "'_blank'") {
	                window.open(elementLink)
	            } else {
	                window.location = (elementLink)
	            }
	        }
	    } else if (click === "slide" || triggered === "true") {

	        if ($(this).hasClass(element + 'Active')) {
	            /*
	            $(this).removeClass(element+'Active').children().find('.moreContent').slideUp('fast', function() {
	            })
	            */
	            return false;
	        } else {
	            $(this).parent().siblings().children().removeClass(element + 'Active').find('.moreContent').hide();
	            $(this).removeClass(element + 'Hover');

	            $(this).addClass(element + 'Active');
	            Cufon.refresh();
	            $(this).children('.moreContent').slideDown();
	            $(this).children('.careersIntroContent').bind('click', function () {
	                $(this).siblings('.moreContent').slideUp('normal', function () {
	                    $(this).parent().removeClass(element + 'Active')
	                })
	            });
	            $(this).children('.careersIntroContent').bind('mouseenter', function () {
	                $(this).addClass('HoverActive');
	                Cufon.refresh();
	            }).mouseleave(function () {
	                $(this).removeClass('HoverActive');
	                Cufon.refresh();
	            });
	        }





	    }



	})	

	
	
}

function getFlickr() {
    $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=69598025@N02&lang=en-us&format=json&jsoncallback=?",
	  function (data) {
	      $.each(data.items, function (i, item) {
	          var imgSrc = item.media.m.replace("_m", "_s");
	          //$("<div style='width:149px; height:280px; overflow:hidden; float: left; margin-right: 2px;' />").attr("id", "photo" + i).appendTo("#flickrFeed");
	          $("<img style=' width:73px; float: left; margin: 0 2px 2px 0; padding:0 !important;' />").attr("src", imgSrc).appendTo("#flickrFeed");
	          if (i == 11) return false;
	      });
	  });	
}

function ajaxFileUpload(handlerName) {
    $("#loading")
    .ajaxStart(function(){
        $(this).show();
        $(".submitButton").hide();
    })
    .ajaxComplete(function(){
        $(this).hide();
        $(".submitButton").show();
    });

    formId = handlerName;
    if (handlerName == "umbMasterForm") {
        handlerName = document.forms[0].FormName.value;

    }

    $.ajaxFileUpload
		(
			{
			    url: '/service/' + handlerName + '.ashx',
			    secureuri: false,
			    fileElementId: 'UploadCv',
			    formData: $("#" + formId).serialize(),
			    dataType: 'json',
			    beforeSend: function () {
			    },
			    complete: function (data, status) {
			        var firstBrace = data.responseText.indexOf("{");
			        var lastBrace = data.responseText.lastIndexOf("}");
			        data.responseText = data.responseText.substring(firstBrace, lastBrace + 1);

			        var response = eval("(" + data.responseText + ")");

			        if (eval(response.success)) {
			            if (handlerName == "AskUs") {
			                $("#AskUsResponse").html("Thank you for your enquiry.");
			            }
			            else if (handlerName == "SendCollection") {
			                $("#SendCollectionResponse").html("Your message has been sent successfully.");
			            }
			            else {
			                popUpForm('', '', '', '', 'close', '', null)  //close form popup

			                //get fields to populate new popup
			                var jobId = response.jobId;
			                var positionTitle = $('#' + jobId).children('.careersIntroContent').children('h4').children('.helvetica').text();
			                var positionLocation = $('#' + jobId).children('.careersIntroContent').children('.careerLocation').text();
			                var positionBlurb = $('#' + jobId).children('.careersIntroContent').children('.blurb').text();

			                if (response.message == 'Your message was sent successfully') {
			                    popUpForm(jobId, positionTitle, positionLocation, positionBlurb, 'open', 'sendApplicationThanks', response)
			                }
			                else if (response.message == 'Your application submitted successfully') {
			                    popUpForm(jobId, positionTitle, positionLocation, positionBlurb, 'open', 'applicationThanks', response)
			                }
			            }

			        }
			        else {
			            if (handlerName == "AskUs") {
			                $("#AskUsResponse").html(response.message);
			            }
			            else {
			                if (response.message == "StartIndex cannot be less than zero.Parameter name: startIndex")
			                    alert("Please make sure a file is attached");
			                else {
			                    alert(response.message);
			                    var validator = $("#" + handlerName).validate();
			                }
			            }
			        }

			    },
			    success: function (data, status) {
			        if (typeof (data.error) != 'undefined') {
			            if (data.error != '') {
			                alert(data.error);
			            } else {
			                alert(data.msg);
			            }
			        }
			    },
			    error: function (data, status, e) {
			        alert(e);
			    }
			}
		)

    return false;

}


function formElements(element) {
	  $("input[type=text][title], input[type=password][title], textarea").each(function() {
	    if($.trim($(this).val()) == "") {
	      $(this).val($(this).attr("title"));
	    } else { 
	    }
	    $(this)
	      .focus(function() {
	        if($(this).val() == $(this).attr("title")) $(this).val("");
	      })
	      .blur(function() {
	        if($.trim($(this).val()) == "") $(this).val($(this).attr("title"));
	      });
	  });
	 $(element).children().find('.sparkbox-custom').sbCustomSelect();
	 $('.file-wrapper input[type=file], .file-wrapper .button').bind('change focus click', SITE.fileInputs);
	 $('.autogrow').growfield({
		min : '42'
	 });	
	
}


function formValidation() {

    $('.submitButton').click(function () {
        $(this).parents('form').submit();
    })


	//add methods
    jQuery.validator.addMethod("acceptOnly", function(value, element, param) { 
        return value.match(new RegExp("^" + param + "$")); }); 
      
      /** To DO: include space using reg expression * */  
	jQuery.validator.addMethod("acceptOnlySpace", function(value, element, param) { 
	    return value.match(new RegExp("^[\p{L} \.'\-]" + param + "$")); });          
	    
	  
	jQuery.validator.addMethod("notEqual", function(value, element, param) {
	    return this.optional(element) || value != param;
	  }, "This field is required.");
	  
	jQuery.validator.addMethod("onlyEqual", function(value, element, param) {
	    return this.optional(element) || value == param;
	  }, "This field is required.");    
	  
	  
	jQuery.validator.addMethod('dependsOn', function (value, element, param) {
	    return this.optional(element) || value != param;
	  }, 'This field is required.');   
	
	
	jQuery.validator.addMethod("defaulText", function(value, element, param) {
	    return this.optional(element) || param == value;
	  }, "Please replace the default text");  
	
	//add rules
	jQuery.validator.classRuleSettings.NameField = {required: true,minlength: 2, notEqual: "Name", acceptOnly: "[a-zA-Z- ]+", number: false, maxlength:175};
	jQuery.validator.classRuleSettings.LnameField = {required: true,minlength: 2, notEqual: "Surname", acceptOnly: "[a-zA-Z- ]+", number: false, maxlength:175};
	jQuery.validator.classRuleSettings.EmailField = {required: true, email: true, maxlength:175 }; 
	jQuery.validator.classRuleSettings.CommentsField = {required: true,minlength: 4, notEqual: "Type your comments here"};
	jQuery.validator.classRuleSettings.CellphoneField = {required: true, notEqual: "Contact number", notEqual:"Contact number", number: true, acceptOnly: "[0][0-9]{0,255}", minlength: 10,maxlength: 10  };
	jQuery.validator.classRuleSettings.Upload = { required: true };

	
	$('form').each(function(){
		
	    $('.CommentsField').live('blur',function(){
		    if ( $(this).hasClass('valid') ) {
			    $(this).parent().siblings('.textAreaHandle').css('bottom','4px')
		    } else {
			    $(this).parent().siblings('.textAreaHandle').css('bottom','16px')
		    }
	    })	
		
	    $(this).validate({
		     messages: {
			    Name: { required: "Please specify your Name", notEqual: "Please specify your Name", acceptOnly: "Please specify your Name", minlength:"Please specify your name",maxlength: "Too many characters" },
			    Surname: {required: "Please specify your Surname", acceptOnly: "Please specify your Surname", minlength:"Please specify your surname",maxlength: "Too many characters", notEqual: "Please specify your Surname" },
			    Email: {required: "Email address is required",email: "E.g example@mail.com",maxlength: "Too many characters"},
			    Comments: {required: "Please type in a comment",notEqual: "Please type in a comment", minlength: "Please type in a comment"},
			    CommentsWhatDefinesYou: {required: "Please type in a comment",notEqual: "Please type in a comment", minlength: "Please type in a comment"},
			    CommentsWishList: {required: "Please type in a comment",notEqual: "Please type in a comment", minlength: "Please type in a comment"},
			    Contactnumber: {required: "Is your number valid?",number: "Only use numbers", acceptOnly: "First digit must be 0" ,minlength: jQuery.format("At least {0} numbers required!"), maxlength: jQuery.format("Maximum of {0} numbers allowed!") },
			    UploadCv: { required: "Please upload your CV" },
			    friendsName: { required: "Please specify the recipients Name", notEqual: "Please specify the recipients Name", acceptOnly: "Please specify the recipients Name", minlength:"Please specify the recipients name",maxlength: "Too many characters" },
			    friendsEmail: { required: "The recipients Email address is required",email: "E.g example@mail.com",maxlength: "Too many characters" }
		     },
		    errorPlacement: function(error, element) {
			    if ( element.hasClass("growfieldDummy") ) {
			    } else if(element.hasClass("CommentsField") ) {	
				    element.siblings('.textAreaHandle').css('bottom','16px')
		    	    element.css('margin-bottom','0').wrap('<div style="float:left;clear:left;position:relative;margin-bottom:0;width:100%"></div>')
		    	    error.appendTo(element.parent('div'));			
			    } else if(element.hasClass("Upload") ) {
		    	    error.appendTo(element.parent('div').siblings('.uploadError'));				
			    } else if(element.parents().hasClass("detailsSection")) {
		    	    element.css('margin-bottom','0').wrap('<div style="float:left;clear:left;position:relative;margin-bottom:20px;width:100%"></div>')
		    	    error.appendTo(element.parent('div'));
		        } else {
		    	    element.wrap('<div style="float:left;position:relative;"></div>')
		    	    error.appendTo(element.parent('div'));
		        }
		    },
               submitHandler: function (form) {
                    ajaxFileUpload(form.id);
                }
        });
	
	}); 

}


// Form popup
function popUpForm(jobId, title, location, blurb, type, url, response) {
	
	//define vars
	var title = title;
	var contentContainer = '#container';
	var overlayClass = 'lightBoxOverlay';
	var ajaxContainer = 'formContent';
	
	
	// build elemnts
	var overLay = $('<div />', {
        'class': overlayClass        
    });
	var overLayContent = $('<div />', {
        'class': ajaxContainer        
    });
	
	if ( type === "open" ) {
		// append to document
		$(contentContainer).hide();
		$('body').append(overLay).animate({
        }, 500, function () {
            $(overLay).show();
            $('body').append(overLayContent).animate({
        }, 500, function () {

    if (url === "application") {
        $('.' + ajaxContainer).load('forms/application.html?' + Math.random(), function () {
            $('#formTitle').empty().append(title + ' application');
            $('#formBlurb').empty().append(blurb);
            $('#hidJobTitle').val(title);
            $('#hidJobId').val(jobId);
            $('.careerLocation').empty().append(location);
            Cufon.refresh();
            formElements(this);
            formValidation();

        });
    } else if (url === "applicationThanks") {
        $('.' + ajaxContainer).load('forms/applicationthanks.html?' + Math.random(), function () {
            $('#jobTitle').html(response.jobTitle);
            $('#jobBlurb').html(blurb);
            $('#appName').html(response.name);
            $('#appSurname').html(response.surname);
            $('#appEmail').html(response.email);
            $('#appPhone').html(response.phone);
            $('#appYearsExp').html(response.yearsExp + " year" + (response.yearsExp >1?"s":"" + " work experience."));
            $('#WhatDefinesYou').html(response.whatDefinesYou);
            $('#YourWishList').html(response.wishList);
            $('#Filename').html(response.cv);
            $('#WebUrl').html(response.webUrl);
            Cufon.refresh();

            //formElements(this);
            //formValidation()

        });
    } else if (url === "sendApplication") {
        $('.' + ajaxContainer).load('forms/applicationSend.html?' + Math.random(), function () {
            $('#jobTitle').empty().append(title);
            $('#jobDescription').empty().html(blurb);
            $('#jobDescription .careersBullet').remove();
            $('#jobDescription .sectionRule').remove();
            $('#jobDescription .clearBoth').remove();
            $('#hidJobId').val(jobId);
            $('#hidJobTitle').val(title);
            $('#hidJobDescription').val($('#jobDescription').html());
            Cufon.refresh();
            formElements(this);
            formValidation()

        });
    } else if (url === "sendApplicationThanks") {
        $('.' + ajaxContainer).load('forms/applicationSendThanks.html?' + Math.random(), function () {
            $('#jobTitle').empty().append(title);
            $('#toNameThanks').empty().append(response.toName);
            $('#jobDescription').empty().html("<p>"+blurb+"</p>");
            $('#jobDescription .careersBullet').remove();
            $('#jobDescription .sectionRule').remove();
            $('#jobDescription .clearBoth').remove();
            Cufon.refresh();
            //formElements(this);
            //formValidation()

        });
    }


})
})		
	} else {
		$('.'+ajaxContainer).empty().remove()
		
//        $('.'+overlayClass).animate({
//		    opacity: 0
//		  }, 500, function() {
//			  $(this).empty().remove();
//			  var title = ''
//			  $(contentContainer).show();
//			  mapNav();
//	    });

		$('.' + overlayClass).empty().remove(); //.css('opacity','0');
		$(contentContainer).show();
		mapNav();
	}
}

jQuery.extend(
		  jQuery.expr[ ":" ], 
		  { reallyvisible : function (a) { return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); }}
		);	


function randomInterviews(event) {
	
	var imageCount;
	
	if ( typeof event != 'undefined' ) {
		event.preventDefault()
	} else {
		$('.randomInterviewsClick').bind('click',function(event){
			randomInterviews(event)
		})
		
		imageCount = $('.clientInterview').size()
		
		$('.clientInterview').each(function(i){
			$(this).hide();
		})
		randomElements = jQuery(".clientInterview").get().sort(function(){ 
			  return Math.round(Math.random())-0.5
		}).slice(0,1)	
		
		$(randomElements).css('opacity','1').show();
		
		return false;
		
	}


	check();

	function check() {
		if ( $('.clientInterview:reallyvisible').next().hasClass('clientInterview') ) {
			$('.clientInterview:reallyvisible').fadeOut('normal',function(){
				$(this).next().fadeIn()
			})
		} else {
			$('.clientInterview:reallyvisible').fadeOut('normal',function(){
				$('.clientInterview').eq(0).fadeIn()
			});
			
		}

	}		
	
}




function randomQuotes(event) {
	
	if ( typeof event != 'undefined') {
		event.preventDefault()
	} else {

		$('.randomQuotes').children('p').each(function(i){
			$(this).hide();
		})
	
		$('.randomQuotesClick').bind('click',function(event){
			randomQuotes(event)
		})
		randomElements = jQuery(".randomQuotes").children('p').get().sort(function(){ 
			  return Math.round(Math.random())-0.5
		}).slice(0,1)	
		if($.browser.msie && parseInt($.browser.version, 10) == 7) {
			 $(randomElements).css('opacity','1').css('display','inline').css('float','left')
		} else {
			 $(randomElements).css('opacity','1').css('display','table-cell')
		}
		
		
		 
		 return false;
	}
	
	check();

	function check() {
	
		randomElements = jQuery(".randomQuotes").children('p').get().sort(function(){ 
			  return Math.round(Math.random())-0.5
		}).slice(0,1)
		var currentText = $('.randomQuotes').children('p:reallyvisible');
	
		
		if ( currentText.text() === $(randomElements).text() ) {
			check();
		} else {
			$('.randomQuotes').children('p').animate({
				opacity: 0
			  }, 500, function() {
				  $(this).hide()
					if($.browser.msie && parseInt($.browser.version, 10) == 7) {
						 $(randomElements).css('opacity','1').css('display','inline')
					} else {
						 $(randomElements).css('opacity','1').css('display','table-cell')
					}
			});			
			 
		}
	}		
}


//function get queryString
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

//Job specifc job
function loadSpecificJob() {
	var queryString =  getUrlVars();
	var jobId = getUrlVars()["jobId"];
	$('#'+jobId).trigger('click','true');
}


function returnDefault(originalPosition) {
	elementPosition = $('ul.showCaseTimelineList li.active').position();
	elementWidth = $('ul.showCaseTimelineList li.active').children('a').width()/2;
	elementWidthFull = $('ul.showCaseTimelineList li').width();
	pointerWidth = $('.showCaseTimelinePointer').width()/2;	
	
	var index = $('ul.showCaseTimelineList li.active').index();
	if ( index < 3 ) {
		var fixWidth = 152;
		//$('.showCaseTimeLineTrackActive').width(152)
	} else {
		var fixWidth = 980;
		//$('.showCaseTimeLineTrackActive').width(980)
	}
	

	$('.showCaseTimelinePointer').stop(true, false).animate({
	    left: elementPosition.left+pointerWidth+elementWidth
	  }, 500, function() {
			$('.showCaseTimeLineTrackActive').stop(true, false).animate({
			    left: (elementPosition.left+elementWidthFull)-152,
			    width: fixWidth
			  }, 500, function() {
			});			  
	});		
}


//Timeline
function timelineControls() {
	
	//define vars
	var elementPosition;
	var elementWidth;
	var pointerWidth;	
	var originalPosition;
	var elementWidthFull;
	var t;
	
	
	//get position
	function getPosition(element){
		elementPosition = $(element).position();
		elementWidth = $(element).children('a').width()/2;
		elementWidthFull = $(element).width();
		pointerWidth = $('.showCaseTimelinePointer').width()/2;			
	}
	
	//animate position
	function animatePosition(){
		$('.showCaseTimelinePointer').stop(true, false).animate({
		    left: elementPosition.left+pointerWidth+elementWidth
		  }, 500, function() {
			  	var trackWidth = (elementPosition.left+elementWidthFull)-152
			  	if (elementPosition.left+elementWidthFull > 456) {
			  		trackWidth = 456
			  		$('.showCaseTimeLineTrackActive').width(980)
			  	} else {
			  		$('.showCaseTimeLineTrackActive').width(152)
			  	}
			  
				$('.showCaseTimeLineTrackActive').stop(true, false).animate({
				    left: trackWidth
				  }, 500, function() {
				});				  
		});	


		
		
	}
	
	function returnOriginalPosition() {
		return $('.showCaseTimelinePointer').position()
	}
	
	
	$('ul.showCaseTimelineList li').each(function(){
		
		if ( $(this).hasClass('active')) {
			getPosition(this)
			animatePosition()
			originalPosition = returnOriginalPosition();
		}
		
		$(this).children('a').mouseenter(function(){
			clearTimeout(t);
			var parent = $(this).parent()
			getPosition(parent)
			animatePosition()	
	    }).mouseleave(function(){
	    	t = setTimeout("returnDefault()",1500);		
	    });	
	})
}


function addToCollection(projectId) {

    //// update cookie

    //read current cookie
    var cookie = $.cookie('aquaOnlineCollection')

    //count the current number of ids -> use [count]
    var re = /;/g;
    for (var count = 0; re.exec(cookie); ++count);
    var newProjectId = count + 1;

    //create cookie
    var newString;
    var currentId = projectId;
    //	var identify = "projectId";
    //	if ( cookie === "" ) 
    //		var newString = identify+newProjectId+"="+currentId
    //	else
    //        var newString = cookie + "&" + identify + newProjectId + "=" + currentId

    if (!cookie)
        newString = currentId + ";";
    else {
        if (!cookie.match(currentId))
            newString = cookie + currentId + ";";
        else
            newString = cookie;
    }
    $.cookie("aquaOnlineCollection", newString, { expires: 365, path: '/' });

    //Check collection
    checkCollection();
    window.location.href = window.location.href;
}

function removeFromCollection(projectId) {

    //// update cookie

    //read current cookie
    var cookie = $.cookie('aquaOnlineCollection')

    //count the current number of ids -> use [count]
    var re = /;/g;
    for (var count = 0; re.exec(cookie); ++count);
    var newProjectId = count + 1;

    //create cookie
    var newString;
    var currentId = projectId;
    //	var identify = "projectId";
    //	if ( cookie === "" ) 
    //		var newString = identify+newProjectId+"="+currentId
    //	else
    //        var newString = cookie + "&" + identify + newProjectId + "=" + currentId

    if (!cookie)
        newString = currentId + ";";
    else {
        if (cookie.match(currentId))
            newString = cookie.replace(currentId + ";", "");
    }
    $.cookie("aquaOnlineCollection", newString, { expires: 365, path: '/' });

    //Check collection
    checkCollection();

}


function checkCollection() {
    //read current cookie
    var cookie = $.cookie('aquaOnlineCollection');
    $("#projIDs").val(cookie);
    //count the current number of ids -> use [count]
    var re = /;/g;
    for (var count = 0; re.exec(cookie); ++count);
    {
        //add required objects
        //alert(cookie[count]);

    }

    //Get collection count
    var collectionCount = count;
    $('#collectionCount').empty().append(collectionCount);

}

function closeCollection() {
	$('.myCollectionWrapper').trigger('click')
}

function removeProjectID(id) {
    if ($('#projIDs').val().match(id)) {
        $('#projIDs').val($('#projIDs').val().replace(';' + id, ''));
    }
}

function addProjectID(id) {
    if (!$('#projIDs').val().match(id)) {
        $('#projIDs').val($('#projIDs').val()+';'+id);
    }
}

function showcaseMyCollection() {
	


	//Check collection
	checkCollection()
	
	//Bind slider click
	$('.myCollectionWrapper').bind('click', function (event) {
	    event.preventDefault();


	    if ($('.myCollectionSlider').hasClass('myCollectionSliderActive')) {
	        $('.myCollectionSlider').slideUp('normal', function () {
	            $('.myCollectionWrapper').removeClass('myCollectionWrapperActive')
	            $(this).removeClass('myCollectionSliderActive');
	            $('.myCollectionThumb').unbind('click');
	        })
	    } else {
	        $('.myCollectionSlider').slideDown('normal', function () {
	            $('.myCollectionWrapper').addClass('myCollectionWrapperActive')
	            $(this).addClass('myCollectionSliderActive')
	            $('.myCollectionThumb').bind('click', function () {
	                if ($(this).siblings('.myCollectionShare_icon').hasClass('myCollectionShare_icon_active')) {
	                    $(this).siblings('.myCollectionShare_icon').removeClass('myCollectionShare_icon_active')
	                    removeProjectID($(this).parent().attr('id').replace('my', ''));
	                } else {
	                    $(this).siblings('.myCollectionShare_icon').addClass('myCollectionShare_icon_active')
	                    addProjectID($(this).parent().attr('id').replace('my', ''));
	                }
	            });
	            /*
	            $('.myCollectionThumb').bind('mouseenter',function(){
	            if ( $(this).siblings('.myCollectionShare_icon').hasClass('myCollectionShare_icon_active') ) {
	            $(this).siblings('.myCollectionShare_icon').removeClass('myCollectionShare_icon_active')
	            } else {
	            $(this).siblings('.myCollectionShare_icon').addClass('myCollectionShare_icon_active')
	            }
	            }).bind('mouseleave',function(){
	            if ( $(this).siblings('.myCollectionShare_icon').hasClass('myCollectionShare_icon_active') ) {
	            $(this).siblings('.myCollectionShare_icon').removeClass('myCollectionShare_icon_active')
	            } else {
	            $(this).siblings('.myCollectionShare_icon').addClass('myCollectionShare_icon_active')
	            }
	            });	
	            */
	        })
	    }
	})
	
	//Bind email send
//	$('.myCollectionButton_send').bind('click',function(){
//		
//		if ( $('.collectionEmailSent').hasClass('collectionEmailSentActive') ) {
//			$(this).removeClass('myCollectionRemove_iconActive')
//			$('.collectionEmailSent').slideUp('normal',function(){
//				$(this).removeClass('collectionEmailSentActive')
//				$('p#emailActive').hide()
//			})			
//		} else {
//			$(this).addClass('myCollectionRemove_iconActive')
//			formValidation()
//			$('.collectionEmailSent').slideDown('normal',function(){
//				$(this).addClass('collectionEmailSentActive')
//				$('p#emailActive').show()
//			})			
//		}
//	})
//	
	
	//Bind add to collection click
	$('.showCaseImageWrapper .showCaseItemHover a').bind('click',function(event){
		event.preventDefault()
		var projectId = $(this).parent().parent().parent().attr('id').split('projectId')[1]
		addToCollection(projectId)
	})
	
	$('.showCaseImageWrapper img').bind('click',function(event){
		event.preventDefault()
		$(this).parent().siblings('.clickThroughs').children('.internal').each(function(i){
			if ( i === 1) {
				return false;
			}
			window.location = this

		})
	})

//Bind add to collection click
$('.myCollectionRemove_icon').bind('click', function () {
    var projectId = $(this).parent().attr('id').split('my')[1]
    var elementId = $(this).parent().attr('id')
    //addToCollection(projectId)
    //alert(projectId);
    $("#" + elementId).fadeOut(400, function () { $(this).remove() });
    removeFromCollection(projectId)
})

}


//Client work ticker
function clientWorkTicker() {
	
	
	$('ul.aboutClientList li p span.client').each(function(){
		$(this).mouseenter(function(){
			var textTitle = $(this).text()
			var textToDisplay = $(this).attr('rel');



			$(this).parents('ul.aboutClientList').siblings('h4').empty().append(textToDisplay);
			Cufon.refresh();
			/*
			$('#clientBlurb').empty().append('<span>'+textToDisplay+'</span>');
			$('#clientBlurb').show().stop(true, false).animate({
				   width: 350
			  }, 500, function() {
			});
			*/
		})
		$(this).mouseleave(function(){
			
			$(this).parents('ul.aboutClientList').siblings('h4').empty().append('The list');
			Cufon.refresh();
			
			/*
			$('#clientBlurb').show().animate({
				   width: 0
			  }, 500, function() {
				  $('#clientBlurb').hide()
			});
			*/			
			
		})	
	})
	
	

}


//scroll to
function goToByScroll(id){
	
	var bodyHeight = $('body').outerHeight()
	
	var footerHeight =  $("#"+id).outerHeight();
	//console.log(footerHeight)


//	$('body').animate({ scrollTop: $(document).height() }, 3000, 'swing', function () {
// 	     //done
//	});

	$.scrollTo("#contactUs", 1500, { easing: 'easeOutExpo' });
}

// lightBox
function mapLightBoxNav(imgIndex) {

    //next image
    var nextImageHref = imgIndex++;
    //count items
    var itemCount = $('.casestudy_gallery ul li a').parent().siblings().size()


    if (itemCount === imgIndex) {
        imgIndex = 0;
    } else if (1 === imgIndex) {
        imgIndex = 1
    }
    var nextimgUrl = $('.casestudy_gallery li').eq(imgIndex).children('a').attr('href')
    var nextTitle = $('.casestudy_gallery li').eq(imgIndex).children('a').children('img').attr('rel')

    //prev image
    var previmgUrl = $('.casestudy_gallery li').eq(imgIndex - 2).children('a').attr('href')
    var prevTitle = $('.casestudy_gallery li').eq(imgIndex - 2).children('a').children().attr('rel')

    $('#galleryNext').bind('click', function () {
        $('#controls').show().animate({
            top: -40
        }, 500, function () {
            $(this).hide()
            $('#galleryImageContainer').addClass('loading').children('img').fadeOut('normal', function () {
                $(this).remove();
                loadimage(nextimgUrl, imgIndex, nextTitle)
            })
        });
    })

    $('#galleryPrev').bind('click', function () {
        $('#controls').show().animate({
            top: -40
        }, 500, function () {
            $(this).hide()
            $('#galleryImageContainer').addClass('loading').children('img').fadeOut('normal', function () {
                $(this).remove();
                loadimage(previmgUrl, imgIndex - 2, prevTitle)
            })
        });
    })
}

function loadimage(imgUrl, imgIndex, title) {
    $('#galleryNext, #galleryPrev').unbind('click')
    var img = new Image();

    // wrap our new image in jQuery, then:
    $(img).load(function () {
        $(this).hide();
        $('#galleryImageContainer').removeClass('loading').append(this);
        $(this).fadeIn('normal', function () {
            //animate controls
            $('#controls').show().animate({
                top: 0
            }, 500, function () {
                mapLightBoxNav(imgIndex++)
            });
        });
    })

     .error(function () {
         // notify the user that the image could not be loaded
     })
     .attr('src', imgUrl);

    // update title
    if (typeof title === "undefined" || title === "") {
        title = '';
    }
    $('.imageGallerySpan').empty().append(title)



}

function buildCasestudyGallery(currentItem, totalItems) {
	
	//define vars
	var title = title;
	var contentContainer = '#container';
	var overlayClass = 'lightBoxOverlay';
	var ajaxContainer = 'galleryContent';
	
	
	// build elements
	var overLay = $('<div />', {
        'class': overlayClass        
    });
	var overLayContent = $('<div />', {
        'class': ajaxContainer        
    });
	
	
	$(contentContainer).hide();
	$('body').append(overLay).animate({
	  }, 500, function() {
	    $(overLay).fadeIn();
	    $('body').append(overLayContent).animate({
		  }, 500, function() {
			  
			 // get galleryHeading
			 var galleryHeading = $('.casestudiesIntroduction h2').text()
			 var gallerySubheading = $('.casestudiesIntroduction h3').text()
			 
			 // current image
			 var imgUrl = $('.casestudy_gallery li').eq(currentItem).children('a').attr('href')
			 var title = $('.casestudy_gallery li').eq(currentItem).children('a').children('img').attr('rel')
			   
			 $('.'+ajaxContainer).load('/templates/galleryTemplate.html?'+Math.random(), function() {
				 
				 $('#mainHeading').empty().append(galleryHeading);
				 $('#subHeading').empty().append(gallerySubheading)				 
				 Cufon.refresh();
				 
				 
				 $('.lightBoxClose').bind('click',function(){
						$('.'+ajaxContainer).empty().remove()
						$('.'+overlayClass).animate({
						    opacity: 0
						  }, 500, function() {
							  $(this).empty().remove();
							  var title = ''
							  $(contentContainer).show();	
					  	});						 
				 })	
				 
				 
				 
				 // Load image
	            loadimage(imgUrl, currentItem, title)				 
			});			 
		  })
	});
	
	
}

function galleryLightBoxInt() {
	
	//bind click
	$('.casestudy_gallery li a').bind('click',function(event){
		event.preventDefault();
		
		//count gallery items
		var galleryRel = $(this).attr('rel')
		var itemIndex = $(this).parent().index();  //will use this to setup current gallery item
		var itemCount = $(this).parent().siblings().size()
		
		buildCasestudyGallery(itemIndex,itemCount)
	})
}


function homePageSlider() {
    $('#headerImages.homePage').mouseenter(function () {
        $('.sliderControls').fadeIn()

        $('.homePrev').bind('click', function () {
            $('a.nivo-prevNav').trigger('click')
        })

        $('.homeNext').bind('click', function () {
            $('a.nivo-nextNav').trigger('click')
        })
    })

    $('#headerImages.homePage').mouseleave(function () {
        $('.sliderControls').fadeOut();
        $('.homePrev,.homeNext').unbind('click');
    })
	
	$('#slider').nivoSlider({
        effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
        animSpeed: 500, // Slide transition speed
        pauseTime: 5000, // How long each slide will show
        beforeChange: function(){
        	$('#slider').append('<div class="wrapper" style="position:absolute;width:100%;height:100%;background:#ffffff"></div>')
        },
        afterChange: function(){
        	$('#slider').children('.wrapper').remove()
        }        
	});
}

function blogNavigation(position) {
	
}

function shareOnTwitter(url, tweet) {
    tweet = tweet.replace(" - ", " - @")
    url = url.substr(1);
    tweet += " http://localhost:8081/showcase.aspx?p=" + url;
    window.open('http://twitter.com/share?&text=' + tweet, 'twitterShare', 'width=500,height=400')
}

function shareCaseStudyOnTwitter(url, tweet) {
    tweet += "  " + url;
    window.open('http://twitter.com/share?&text=' + tweet, 'twitterShare', 'width=500,height=400')
}

function shareOnFacebook(page, url, message) {
    url = url.substr(1);
    url="http://localhost:8081/"+page+"?p=" + url;
    window.open('http://www.facebook.com/sharer/sharer.php?u=' + url + "&t=" + message, 'Facebook Share', 'width=640,height=440')
}

function shareCaseStudyOnFacebook(url, message) {
    window.open('http://www.facebook.com/sharer/sharer.php?u=' + url + "&t=" + message, 'Facebook Share', 'width=640,height=440')
}

function blogFunctions() {
	//search focus active

	$('#blogSearchContainer').children('input').focusin(function(){
		$(this).siblings('.searchInputIconContainer').children('.searchInputIcon').addClass('searchInputIconActive')
	})
	$('#blogSearchContainer').children('input').focusout(function(){
		$(this).siblings('.searchInputIconContainer').children('.searchInputIcon').removeClass('searchInputIconActive')
	})
	
	
	$('#blogNavigation p').each(function(){
		$(this).mouseenter(function(){
			var elementPosition = $(this).position();
			var elementWidth = $(this).width()/2;
			var actualPosition = elementPosition.left-elementWidth
			console.log(actualPosition)
		});
		$(this).mouseenter(function(){
			
		})		
	})
}

function styleFixes() {
    $('.casestudy_gallery ul li:nth-child(6n)').css('margin-right', '0');
    var blogRightContent = $('#blogMoreContent').height();
    var blogLeftContent = $('#blogLanding').height();
    if (blogRightContent > blogLeftContent) {
        $('#blogLanding').height(blogRightContent)
    } else {
        //we can leave it
    }
    //quick fix for case study close
    var referer = getUrlVars()["ref"];
    if (typeof referer === "undefined" || referer === "") {
        //leave
    } else {
        if (referer === "homepage") {
            $('.lightBoxClose').children('a').attr('href', '../');
        }
    }

}


$(document).ready(function () {
    // Load required functions
    repositionHeader();
    loadFonts();
    applyDivHovers('homeSnippet', 'click');
    //formElements();
    //formValidation();
    galleryLightBoxInt();
    homePageSlider();
    styleFixes();






    //hovers
    $('ul.staffInterviews li').mouseenter(function () {
        $(this).append('<div class="profileVideoThumbHover iconSet"></div>')
        $('.profileVideoThumbHover').fadeIn()
    })

    $('ul.staffInterviews li').mouseleave(function () {
        $('.profileVideoThumbHover').fadeOut()
        $('.profileVideoThumbHover').remove()
    });

    if ($('textarea').hasClass('autogrow')) {
        $('.autogrow').growfield({
            min: '42'
        });
    }

    $('.sparkbox-custom').sbCustomSelect();


    //Apply for position
    $('.applyForPosition').click(function (event) {
        var positionTitle = $(this).parents('.moreContent').siblings('.careersIntroContent').children('h4').children('.helvetica').text();
        var positionLocation = $(this).parents('.moreContent').siblings('.careersIntroContent').children('.careerLocation').text();
        var positionBlurb = $(this).parents('.moreContent').siblings('.careersIntroContent').children('.blurb').text();
        var jobId = $(this).parents('.moreContent').parent().attr('id');
        popUpForm(jobId, positionTitle, positionLocation, positionBlurb, 'open', 'application', null)
        //popUpForm(positionTitle, positionLocation,'open','thankYou')
    })

    //Send position
    $('.sendJobButton').click(function (event) {
        var positionTitle = $(this).parents('.moreContent').siblings('.careersIntroContent').children('h4').children('.helvetica').text();
        var positionLocation = $(this).parents('.moreContent').siblings('.careersIntroContent').children('.careerLocation').text();
        var positionDescription = $(this).parents('.moreContent').html();
        var jobId = $(this).parents('.moreContent').parent().attr('id');
        popUpForm(jobId, positionTitle, positionLocation, positionDescription, 'open', 'sendApplication', null)
        //popUpForm('', '','open','sendApplicationThanks')
    })

    //to do -add a function for this

    $('ul.showcaseItems li .showCaseImageWrapper').mouseenter(function () {
        $(this).children('.showCaseItemHover').show()
    })

    $('ul.showcaseItems li .showCaseImageWrapper').mouseleave(function () {
        $(this).children('.showCaseItemHover').hide()
    })


    $("ul.showCaseClientsLogo li img").mouseenter(function () {
        //var imagesrc = $(this).attr('src').split('up.')[0];
        $(this).attr('src', $(this).attr('hover'))
    }).mouseleave(function () {
        //var imagesrc = $(this).attr('src').split('over.')[0];
        $(this).attr('src', $(this).attr('out'))
    });




    $('#plax2').fadeIn('slow', function () {
        $('#plax1').css('top', '-20px').css('opacity', '0').show().animate({
            opacity: 1,
            top: "+=20px"
        }, 500, 'easeOutCirc', function () {
        });
    })

})

function repositionHeader() {
	var windowWidth = $(window).width()
	var headerImageWidth = $('.layerContainer').width()

	if ( windowWidth < headerImageWidth ) {
		var widthDifference = (headerImageWidth-windowWidth)/2;
		$('.layerContainer').css('left','-'+widthDifference+'px')
	} else {
		$('.layerContainer').css('left',0)
	}
	
	
}


$(window).resize(function() {
	mapNav();
	repositionHeader();
});


function solutionsAnimation() {
    i = 0;
    rotation();
    solArray = [];
    solArray['Research'] = "The web is a rich source of real-time consumer and competitor data. Our dedicated research team provides field research, online panel research and desktop research.";
    solArray['Analytics'] = "Expert implementation of analytics software delivers real-time tracking and insights. This is a robust digital measurement solution.";
    solArray['Strategy'] = "Through our extensive experience, we crafted proprietary methodologies that ensure a rigorous approach to strategy.";
    solArray['Usability'] = "An interface needs to be both usable and useful. We take a user-centric approach (as opposed to focusing merely on the business owner&rsquo;s requirements) when designing applications. ";
    solArray['Creative'] = "Creative executions display the ability to delight and innovate, yet at the same time stay true to strategic intent and key consumer insights. It&rsquo;s an art we strive to perfect with each piece of work.";
    solArray['Technology'] = "A deep technical competence is essential to ensure that a business like ours keep up with advancements and is able to execute robustly. We have an extensive team of highly skilled software engineers that are continually innovating and deploying on the latest technology platforms.";
    solArray['CRM'] = "The consumer is the hero and their opinion matters. The advent of digital technology and social media has transformed traditional CRM thinking. We have merged the traditional with the digital, to provide a truly integrated offering.";
    solArray['Social Media'] = "We provide a full social media service, that enables us to engage the social communities around brands, to converse with key influencers in relevant industries, to listen to conversations and to manage reputation.";
    solArray['Bought Media'] = "Through search marketing we can advertise there where consumers demonstrate deliberate intent. With the advent of PPC models, brands need only pay for the media that the customers consume. We provide Display and SEM services across internet and mobile channels.";
    //$('#offeringImageRotation').hide();

    $('.offeringLeft a').click(function () {
        clickedVar = true;
        //clearInterval(rotateIcon);
    });
    $('.offeringLeft a').hover(function () {
        $('#offeringImageRotation').hide();
        i = $(this).index();
        if (i == 9) {
            i = 0;
        }
        stopRotation(); //Hover effects on list-item
        clickedVar = false;
        imgTitle = $(this).attr("title"); //Get Main Image URL
        $('#offeringImageRotation').css({ 'background-image': 'url(images/solutions/' + imgTitle + '.jpg)' }, $('#offeringImageRotation').fadeIn(500));
        changedTitle = imgTitle.replace("%20", " ");
        this.title = changedTitle;
        $('.quoteText').html(solArray[changedTitle]);
        $('.quoteOfferingHeading').html(changedTitle + "<span class=\"col_blue fullStop\">.</span>");
        offerHeight = $('.offeringRight').fadeIn(200).height();
        blockHeight = offerHeight - 150;
        padTop = ((645 - blockHeight) / 2) - 30;
        $('.offeringRight').css({ 'padding-top': padTop });
        Cufon.refresh();
    }, function () {
        this.title = imgTitle;
        //$('#offeringImageRotation').fadeOut(300);
        if (clickedVar != true) {
            rotation();
        }
    });
    $('.offeringLeft a').click(function () {
        $('.quoteText').html(solArray[changedTitle]);
        $('.quoteOfferingHeading').html(changedTitle + "<span class=\"col_blue fullStop\">.</span>");
        $('.offeringRight').fadeIn(200);
        Cufon.refresh();
    });
}

function rotation() {
    rotateIcon = setInterval(nextIcon, 10000);
}
function stopRotation() {
    clearInterval(rotateIcon);
}
function nextIcon() {
    var rotArray = [];
    rotArray[0] = "Analytics";
    rotArray[1] = "Strategy";
    rotArray[2] = "Usability";
    rotArray[3] = "Creative";
    rotArray[4] = "Technology";
    rotArray[5] = "CRM";
    rotArray[6] = "Social%20Media";
    rotArray[7] = "Bought%20Media";
    rotArray[8] = "Research";

    $('#offeringImageRotation').hide();
    $('#offeringImageRotation').css({ 'background-image': 'url(images/solutions/' + rotArray[i] + '.jpg)' }, $('#offeringImageRotation').fadeIn(300));
    var changedTitle = rotArray[i].replace("%20", " ");
    $('.offeringRight').fadeOut(500).hide();
    $('.quoteText').html(solArray[changedTitle]);
    $('.quoteOfferingHeading').html(changedTitle + "<span class=\"col_blue fullStop\">.</span>");
    offerHeight = $('.offeringRight').fadeIn(200).height();
    blockHeight = offerHeight - 150;
    padTop = ((645 - blockHeight) / 2) - 30;
    $('.offeringRight').css({ 'padding-top': padTop });
    Cufon.refresh();
    if (i < 8) {
        i++;
    } else {
        i = 0;
    }
};



