/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();;

jQuery(document).ready(function ($) {

	/* ------------------ GLOBAL ------------------ */
	
	preloadImages($, [
		'/sites/all/themes/inVentiv/images/awards-historical-minus.png',
		'/sites/all/themes/inVentiv/images/body_global_collapsible_collapsed.png',
		'/sites/all/themes/inVentiv/images/body_global_collapsible_expanded.png',
		'/sites/all/themes/inVentiv/images/body_global_h4_minus.png',
		'/sites/all/themes/inVentiv/images/body_global_h4_plus.png',
		'/sites/all/themes/inVentiv/images/header_nav_arrows_over.gif'
	]);
	
	setupShowMoreShowLess($);
	setupExpandableHeaders($);
    setupPaging($);

	/* ------------------ PAGE SPECIFIC ------------------ */
	
    twoCharYear($, '.page-about-us-newsroom #main-wrapper .pane-content .news-date span');
    twoCharYear($, '.page-home #main-wrapper .pane-content .field-content .carousel_date');
    setFirstYearActive($);
    checkCompanyURL($);
    checkYearTD($);

	pageSpecificCode($);

})

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** giant switch statement based on page URL ******/
/****** SNM 2011.11.05                           ******/

function pageSpecificCode($) {
	
	var currentPage = window.location.pathname;

	switch(currentPage) {
	
		/* --------------------------------------------     ABOUT US    -------------------------------------------- */
	    case '/about_us/leadership_team':
	        $('.page-about-us-leadership-team #main-wrapper .pane-content .h4Wrapper:first').click();
		break;
	
		/* --------------------------------------------  OUR SOLUTIONS  -------------------------------------------- */
		case '/solutions/companies/selling_solutions':
	        $('.selling-solution-intro .accordion-content').css('display', 'block');
	        $('.selling-solution-intro .accordion-wrapper').html('See less');
	        $('.selling-solution-intro .accordion-wrapper').removeClass('accordion-collapsed').addClass('accordion-expanded');
	    break;

		case '/solutions/companies/inventiv_recruitment_services':
	        $('.recruitment .accordion-content').css('display', 'block');
	        $('.recruitment .accordion-wrapper').html('See less');
	        $('.recruitment .accordion-wrapper').removeClass('accordion-collapsed').addClass('accordion-expanded');
	        $('html, body').animate({ scrollTop: 850 }, 1);
	    break;

		case '/solutions/companies/learning_and_development':
	        $('.learning .accordion-content').css('display', 'block');
	        $('.learning .accordion-wrapper').html('See less');
	        $('.learning .accordion-wrapper').removeClass('accordion-collapsed').addClass('accordion-expanded');
	        $('html, body').animate({ scrollTop: 1100 }, 1);
	    break;

		case '/solutions/companies/therapeutics_institute':
	        $('.therapeutic .accordion-content').css('display', 'block');
	        $('.therapeutic .accordion-wrapper').html('See less');
	        $('.therapeutic .accordion-wrapper').removeClass('accordion-collapsed').addClass('accordion-expanded');
	        $('html, body').animate({ scrollTop: 1375 }, 1);
	    break;
	
		/* -------------------------------------------- JOBS AND PEOPLE -------------------------------------------- */
	    case '/jobs_people/working_environment':
	        $('h4').addClass('working-at-inventiv-collapsed');
		break;
	
	    case '/jobs_people/diverse_team':
	        //$("#diverse").removeClass('working-at-inventiv-collapsed').addClass('working-at-inventiv-expanded');
	        $('#diverse').find('.working-at-inventiv-div').css('display', 'block');
	        $('#diverse').find('h4').addClass('working-at-inventiv-expanded').removeClass('h4-collapsed').addClass('h4-expanded');;
	        $('#community').find('h4').addClass('working-at-inventiv-collapsed');
	        $('#equal').find('h4').addClass('working-at-inventiv-collapsed');
	        // console.log('diverse');
	    break;

		case '/jobs_people/giving_back_to_community':
	        //$("#community").removeClass('working-at-inventiv-collapsed').addClass('working-at-inventiv-expanded');
	        $('#community').find('.working-at-inventiv-div').css('display', 'block');
	        $('#diverse').find('h4').addClass('working-at-inventiv-collapsed');
	        $('#community').find('h4').addClass('working-at-inventiv-expanded').removeClass('h4-collapsed').addClass('h4-expanded');;
	        $('#equal').find('h4').addClass('working-at-inventiv-collapsed');
	        console.log('community');
	    break;

		case '/jobs_people/equal_opportunity':
	        //$("#community").removeClass('working-at-inventiv-collapsed').addClass('working-at-inventiv-expanded');
	        $('#equal').find('.working-at-inventiv-div').css('display', 'block');
	        $('#diverse').find('h4').addClass('working-at-inventiv-collapsed');
	        $('#community').find('h4').addClass('working-at-inventiv-collapsed');
	        $('#equal').find('h4').addClass('working-at-inventiv-expanded').removeClass('h4-collapsed').addClass('h4-expanded');
	        console.log('equal');
	    break;

	}
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** global functionality for "see less"/"see more" accordions ******/
/****** SNM 2011.11.05                                            ******/

function setupShowMoreShowLess($) {
	
    var clickableDivs = '#main-wrapper .pane-content .accordion-wrapper';

	$(clickableDivs).addClass('accordion-collapsed');
    $(clickableDivs).click(function (e) {

        var divContent = $.trim( $(this).html() );
        if (divContent == 'See more') {
            $(this).html('See less');
            $(this).removeClass('accordion-collapsed').addClass('accordion-expanded');
        } else {
            $(this).html('See more');
            $(this).removeClass('accordion-expanded').addClass('accordion-collapsed');
        }

        $(this).prev().slideToggle('fast');

	    e.preventDefault();
    });
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** global functionality for clickable H4s with plus/minus image ******/
/****** SNM 2011.11.05                                               ******/

function setupExpandableHeaders($) {

    var clickableArea = '#main-wrapper .pane-content div.sectionWrapper .h4Wrapper';
    var h4 = $(clickableArea).find('h4');

    $(h4).addClass('h4-collapsed');

    $(clickableArea).click(function (e) {
	
        var contentDiv = $(this).next();
        contentDiv.slideToggle('fast');

        if ($(this).children().hasClass('h4-collapsed')) {
            $(this).children()
				.removeClass('h4-collapsed')
				.addClass('h4-expanded')
				.removeClass('working-at-inventiv-collapsed')
				.addClass('working-at-inventiv-expanded');
        } else {
            $(this).children()
				.removeClass('h4-expanded')
				.addClass('h4-collapsed')
				.removeClass('working-at-inventiv-expanded')
				.addClass('working-at-inventiv-collapsed');
        }
    });
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** rewrite pagination NEXT LAST FIRST PREV ******/
/****** E HARMS (Tue Nov  1 11:48:48 EDT 2011)  ******/

function setupPaging($) {
    var pageNext = $('#main-wrapper .pane-content .pager-next a');
    var pageLast = $('#main-wrapper .pane-content .pager-last a');
    var pageFirst = $('#main-wrapper .pane-content .pager-first a');
    var pagePrev = $('#main-wrapper .pane-content .pager-previous a');

    $(pageNext).each(function (index, value) {
        var element = $(this).html()
        $(this).html("NEXT");
    })

    $(pageLast).each(function (index, value) {
        var element = $(this).html()
        $(this).html("LAST");
    })

    $(pageFirst).each(function (index, value) {
        var element = $(this).html()
        $(this).html("FIRST");
    })

    $(pagePrev).each(function (index, value) {
        var element = $(this).html()
        $(this).html("PREV");
    })
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** press release rewrite year listing to 2-digit ******/
/****** E HARMS (Tue Nov  1 11:48:19 EDT 2011)        ******/

function twoCharYear($, elem) {
    $(elem).each(function (index, value) {
        var element = $(this).html()
        var elements = element.split('.');
        var shortDate = $(elements[2].substring(2, 4)).text();
        var newDate = elements[0] + '.' + elements[1] + '.' + elements[2].substring(2, 4);
        $(this).html(newDate);
    })
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** press releases / news / pov                       ******/
/****** set first year in list to active on initial load  ******/
/****** E HARMS (Tue Nov  1 11:49:52 EDT 2011)            ******/

function setFirstYearActive($) {
    var prHrefTarget = $('.page-about-us-newsroom-press-releases .pane-content .press-release-years-div tr.row-1 td.col-first');
    var newsHrefTarget = $('.page-about-us-newsroom-news .pane-content .inventiv-news-years-div tr.row-1 td.col-first');
    var povHrefTarget = $('.page-solutions-pov-publications .pov-pub-year-div tr.row-1 td.col-first');
    var pathName = window.location.pathname;
    var pathElements = pathName.split('/');
    var pageNews = "/about_us/newsroom/news";
    var pagePR = "/about_us/newsroom/press_releases";
    var pagePOV = "/solutions/pov_publications";

    if ((pathName == pagePR || pathName == pageNews || pathName == pagePOV) && pathElements[4] == null) {
        $(newsHrefTarget).find('a').addClass('active');
        $(prHrefTarget).find('a').addClass('active');
        $(povHrefTarget).find('a').addClass('active');
    }
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** if link to company has http open in new window, otherwise open orphan pages in domain ******/
/****** E HARMS (Tue Nov  1 11:50:03 EDT 2011)                                                ******/

function checkCompanyURL($) {
    var companyURL = $('.page-solutions-companies #main-wrapper .pane-content .sectionRight');
    companyURL.each(function () {
        $(this).find('a[href^="http://"]').attr('target', '_blank');
        $(this).find('a[href^="/"]')
			.removeClass('href-external')
			.addClass('href-chevron-right');
    })
}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** add / remove pager-last depending on number of items in years for press releases and inventiv in the news ******/
/****** E HARMS (Tue Nov  1 11:49:41 EDT 2011)                                                                    ******/

function checkYearTD($) {
    var newsYearTD = $('.page-about-us-newsroom-news .pane-content .view-in-the-news-years tr.row-1 td');
    var prYearTD = $('.page-about-us-newsroom-press-releases .pane-content .view-press-release-years tr.row-1 td');
    var counter = 0;
    var newsRow1 = $('.page-about-us-newsroom-news .pane-content .view-in-the-news-years tr.row-1');
    var prRow1 = $('.page-about-us-newsroom-press-releases .pane-content .view-press-release-years tr.row-1');

    $(newsYearTD).each(function (index, value) {

        var trimmedHTML = $.trim( $(this).html() );
        if (trimmedHTML == "") {
            if ($(this).hasClass('col-last')) {
                $(this).removeClass('col-last')
            }

            $(this).addClass('empty' + counter);
            counter++;
        }
    })


    $(prYearTD).each(function (index, value) {
        var trimmedHTML = $.trim( $(this).html() );

        if (trimmedHTML == "") {
            if ($(this).hasClass('col-last')) {
                $(this).removeClass('col-last')
            }

            $(this).addClass('empty' + counter);
            counter++;
        }
    })


    $(newsRow1).find('.empty0').prev('td').find('a').addClass('col-last');
    $(prRow1).find('.empty0').prev('td').find('a').addClass('col-last');

}

/* ------------------------------------------------------------------------------------------------------------------------------ */

/****** preload images so they dont blink when loading ******/
/****** E HARMS (Tue Nov  1 11:52:41 EDT 2011)         ******/

function preloadImages($, arrayOfImages) {
    $(arrayOfImages).each(function () {
        (new Image()).src = this;
    });
}

/* ------------------------------------------------------------------------------------------------------------------------------ */
;
var title = document.title;
var bookmarkChromeString = 'To bookmark this page, click the star symbol at the end of the address bar or press Ctrl+D.';
var bookmarkSafariString = 'To bookmark this page, use the Bookmarks menu or press Ctrl+D.';
var bookmarkiPadString = 'To bookmark this page,\r\press the bookmark icon\r\nat the top of your browser.';
var homeInterval, slideshow, carousel;
var isiPad = navigator.userAgent.match(/iPad/i) != null;

jQuery(document).ready(function($){ 

	//global
	tweakModal($);
	
	//header
	setupSearch($);

	//sidebar
	setupPrint($);
	setupBookmark($);
	setupShare($);
	setupSidebarBlocks($);
	
	// page specific
	setupHome($);
	tweakHome($);
	tweakAbout($);

});

//--------------------------------------------------------------------------------------------------------------
//                                        PAGE SPECIFIC TWEAKS
//--------------------------------------------------------------------------------------------------------------

function tweakHome($) {
	var carouselDiv = $(".jcarousel-clip");
	if(carouselDiv) {
		carouselDiv.append('<div class="cover"></div>');
	}
	
	var blocks = $("#home_boxes .box");
	
	blocks.each(function(e) {
		$(this).hover(
			function(e) { $(this).addClass("hover"); },
			function(e) { $(this).removeClass("hover"); }
		);
		$(this).click(function(e) {
			var link = $(this).find('a');
			var linkURL = link.attr('href');
			if( link.hasClass("lightbox-processed") || link.hasClass("lightbox") ) {
				$(this).find('a').click();
			} else {
				window.location = linkURL;
			}
		});
	});
	
}

//--------------------------------------------------------------------------------------------------------------

function setupHome($) {
	
	if(!$("body").hasClass("page-home")) {
		return;
	}
	
	if(isiPad) {
		
		$("#video").hide();
		$("#carousel").show();
		
		initCarousel();
		
		$("#carousel .next").click(function(e) {
			moveHomeForward();
			e.preventDefault();
		});
		
		$("#carousel .prev").click(function(e) {
			moveHomeBackward();
			e.preventDefault();
		});
		
		homeInterval = setInterval("moveHomeForward()", 12000);
		
	} else {
		
		$("#video").show();
		$("#carousel").hide();
		
	}
	
}

function initCarousel() {
	var	el,
		i,
		page,
		slides = [
			'<div id="state1"><a class="link" href="/about_us">Let’s Get Started</a><a class="next" href="#"></a></div>',
			'<div id="state2"><a class="link" href="/solutions">Life-Changing Ideas, World-Changing Realities</a> <a class="next" href="#"></a> <a class="prev" href="#"></a></div>',
			'<div id="state3"><a class="link" href="/solutions/companies/clinical">If It’s Healthcare, inVentiv Health Is There</a> <a class="prev" href="#"></a></div>'
		];

	carousel = new SwipeView('#carousel', {
		numberOfPages: slides.length,
		hastyPageFlip: true
	});

	// Load initial data
	for (i=0; i<3; i++) {
		page = i==0 ? slides.length-1 : i-1;

		el = document.createElement('span');
		el.innerHTML = slides[page];
		carousel.masterPages[i].appendChild(el)
	}
}

function moveHomeForward() {
	if(carousel.page == 2) {
		carousel.prev2();
		return;
	}
	carousel.next();
}

function moveHomeBackward() {
	if(carousel.page == 0) return;
	carousel.prev();
}

//--------------------------------------------------------------------------------------------------------------

function tweakAbout($) {
	if(isiPad) {
		$(".brochure a").click(function(e) {
			$(document).scrollTop(0);
		})
	}
}

//--------------------------------------------------------------------------------------------------------------
//                                        HEADER: SEARCH
//--------------------------------------------------------------------------------------------------------------

function setupSearch($) {
	var searchInput = $("#header #block-simplesearch-simplesearch .form-text");
	searchInput
		.val("Search")
		.focus(function(e) {
			if( $(this).val() == "Search" ) {
				$(this).val("");
			}
		})
		.blur(function(e) {
			if( $(this).val() == "" ) {
				$(this).val("Search");
			}
		});
}

//--------------------------------------------------------------------------------------------------------------
//                                        SIDEBAR ITEM: SHARE
//--------------------------------------------------------------------------------------------------------------

function setIFrameSource(url) {
	var myframe = document.getElementById("share_modal_iframe");
	if(myframe !== null) {
	    if(myframe.src) {
	        myframe.src = url;
		} else if(myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
	        myframe.contentWindow.location = url; 
		} else{ 
			myframe.setAttribute('src', url);
		}
	}
}


function setupShare($) {
	$("#share_modal").animate( {height: 'toggle'}, 1, function() { $(this).css('visibility', 'visible') } );
	
	$("body").append( '<div id="share_overlay" style="display: none;"></div>' );
	$("#page").append( $("#share_modal") );
	
	var overlay = $("#share_overlay");
	overlay.click(function(e) {
		sharePage();
	});
	
	//move share to proper position
	if($("#sidebar_share").length > 0) {
		var newTop = $("#sidebar_share").offset().top + 22;
		var newLeft = $("#sidebar_share").position().left + ( $("#sidebar_share").width() / 2 ) - 355;
		$("#share_modal").css({ 
			'top': newTop+'px', 
			'left': newLeft+'px'
		});
	
		if( !$("body").hasClass('node-type-webform') ) {
			setIFrameSource('/forms/form-share-page');
			// $("#share_modal iframe").attr('src', '/forms/form-share-page');
			// $("#share_modal iframe").location = '/forms/form-share-page';
		} else {
			$("#share_modal").hide();
		}
	}
	
	if($("body").hasClass("page-node-3482")) {
		var inputURL = $("input[name=submitted\\[share_url\\]]");
		var inputTitle = $("input[name=submitted\\[share_title\\]]");
		var inputSubject = $("input[name=submitted\\[subject\\]]");
		var obj = parent.getShareValues();
		inputURL.val(obj.url);
		inputTitle.val(obj.title);
		inputSubject.val(obj.title);
		$("#share_modal").hide();
	}
	
	getShareValues();
}

function sharePage() {
	var overlay = jQuery("#share_overlay");
	var modal = jQuery("#share_modal");
	
	overlay.toggle();
	modal.slideToggle('fast', function() {
		if( overlay.css('display') == 'none' ) {
			jQuery("#share_modal iframe").attr('src', '/forms/form-share-page');
			// setIFrameSource('/forms/form-share-page');
		}
	} );
}

function closeShare() {
	parent.sharePage();
}

function getShareValues() {
	var obj = {};
	obj.url = document.URL;
	obj.title = document.title;
	return obj;
}

//--------------------------------------------------------------------------------------------------------------
//                                        SIDEBAR ITEM: BOOKMARK
//--------------------------------------------------------------------------------------------------------------

function setupBookmark($) {
    // chrome does not permit addToFavorites() function by design 
    if((navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) { 
        $('.addbookmark').attr({ 
            title: bookmarkChromeString, 
            href: 'javascript:addToFavoritesChrome();' 
        });
		return;
    } 
	//ipad too
    if((navigator.userAgent.toLowerCase().indexOf('ipad') > -1)) { 
        $('.addbookmark').attr({ 
            title: bookmarkiPadString, 
            href: 'javascript:addToFavoritesiPad();' 
        });
		return;
    } 
	//safari too
    if((navigator.userAgent.toLowerCase().indexOf('safari') > -1)) { 
        $('.addbookmark').attr({ 
            title: bookmarkSafariString, 
            href: 'javascript:addToFavoritesSafari();' 
        });
		return;
    } 
}

/* simple cross-browser script for adding a bookmark 
    source: http://stackoverflow.com/questions/992844/add-to-browser-favourites-bookmarks-from-javascript-but-for-all-browsers-mine-do 
*/ 
function addToFavorites(url, name) { 
    if (window.sidebar) { // Mozilla Firefox 
        window.sidebar.addPanel(name, url, ""); 
    } else if (window.external) { // IE 
        window.external.AddFavorite(url, name); 
    } else if (window.opera && window.print) { 
        window.external.AddFavorite(url, name); 
    } else { 
        alert("Sorry! Your browser doesn't appear to support this function."); 
    } 
}

function addToFavoritesChrome() {
	alert(bookmarkChromeString);
	return false;
}

function addToFavoritesiPad() {
	alert(bookmarkiPadString);
	return false;
}

function addToFavoritesSafari() {
	alert(bookmarkSafariString);
	return false;
}

//--------------------------------------------------------------------------------------------------------------
//                                        SIDEBAR ITEM: PRINT
//--------------------------------------------------------------------------------------------------------------

function setupPrint($) {
	$("#logo").parent().append('<img src="/sites/all/themes/inVentiv/images/print_logo.gif" class="print_only print_logo" />');
	$("#logo").parent().append('<img src="/sites/all/themes/inVentiv/images/print_tagline.gif" class="print_only print_tagline" />');
}

//--------------------------------------------------------------------------------------------------------------
//                                        SIDEBAR ITEM: BLOCKS
//--------------------------------------------------------------------------------------------------------------

function setupSidebarBlocks($) {
	var blocks = $(".sidebar .block-block");
	
	blocks.each(function(e) {
		$(this).hover(
			function(e) { $(this).addClass("hover"); },
			function(e) { $(this).removeClass("hover"); }
		);
		$(this).click(function(e) {
			var link = $(this).find('a');
			var linkURL = link.attr('href');
			if( link.hasClass("lightbox-processed") || link.hasClass("lightbox") ) {
				$(this).find('a').click();
			} else {
				window.location = linkURL;
			}
		});
	});
}

//--------------------------------------------------------------------------------------------------------------
//                                        MODAL 
//--------------------------------------------------------------------------------------------------------------

function tweakModal($) {
	var container = $("#outerImageContainer");
	
	container.css({
		'position': 'relative'
	});
	
	var closeButton = $("#bottomNavClose").css('background-color','transparent');
	
	closeButton.html('CLOSE');
	closeButton.appendTo(container);

	// remove flash of white from iframes (contact modals etc)
    // 1. Inject CSS which makes iframe invisible
    var div = document.createElement('div'),
        ref = document.getElementsByTagName('base')[0] ||
              document.getElementsByTagName('script')[0];

    div.innerHTML = '&shy;<style> iframe { visibility: hidden; } </style>';

    ref.parentNode.insertBefore(div, ref);

    // 2. When window loads, remove that CSS, making iframe visible again
    window.onload = function() {
        div.parentNode.removeChild(div);
    }
}

function closeModal() {
	window.parent.Lightbox.end();
}
;
function createDelegate(object, method)
{
    return function() { method.apply(object, arguments); };
}

var homePageFlash;
var homePageState = 0;
var homePageState1Time = 0;
var homePageState2Time = 12;
var homePageState3Time = 24;

var homePageState1Nav = '/about_us';
var homePageState2Nav = '/solutions';
var homePageState3Nav = '/solutions/companies/clinical';


var homePageFlashActive = false;

function flashVideoActive ()
{
	homePageFlashActive = true;
}

function flashReady (status)
{
	// console.log (status);
	if (status.success)
	{
		homePageFlash = status.ref;
	}
}

function onTimeUpdate (e)
{
	var time;
	if (typeof(e)=='number')
	{
		time = e;
	}
	else
	{
		time = this.currentTime;
	}

	var newPageState;

	if (time < homePageState2Time)
	{
		newPageState = 1;
	}
	else if (time < homePageState3Time)
	{
		newPageState = 2;
	}
	else
	{
		newPageState = 3;
	}

	if (homePageState != newPageState)
	{
		homePageState = newPageState;
		jQuery ('#video_controls #state1, #video_controls #state2, #video_controls #state3').removeClass('active');
		var activeStr = '#video_controls #state' + homePageState;
		jQuery (activeStr).addClass('active');
	}
}

function videoGoTo (state)
{
	var time = 0;

	switch (state)
	{
		case 1:
			time = homePageState1Time;
			break;
		case 2:
			time = homePageState2Time;
			break;
		case 3:
			time = homePageState3Time;
			break;
	}

	if (homePageFlashActive)
	{
		homePageFlash.setTime (time);

	}
	else
	{
		var video = jQuery('#home_page_video')[0];
		video.currentTime = time;
	}
}



function onVideoClick (e)
{
	var time;
	if (homePageFlashActive)
	{
		time = homePageFlash.getTime();

	}
	else
	{
		if (this.readyState < 2)
		{
			this.play();
			return;
		}
		time = this.currentTime;
	}

	var nav;
	if (time < homePageState2Time)
	{
		nav = homePageState1Nav;
	}
	else if (time < homePageState3Time)
	{
		nav = homePageState2Nav;
	}
	else
	{
		nav = homePageState3Nav;
	}

	window.location.href = nav;
}

jQuery(document).ready(function($)
{
	var video = $('#home_page_video')[0];
	try 
	{
		video.addEventListener ("timeupdate", createDelegate(video, onTimeUpdate), false);
		video.addEventListener ("click", createDelegate(video, onVideoClick), false);
	}
	catch (err) { }

	$('#state1').click( function () { videoGoTo(1); } );
	$('#state2').click( function () { videoGoTo(2); } );
	$('#state3').click( function () { videoGoTo(3); } );

	$('.view-main-company-listing-commercial h2.communications').first().show();
	$('.view-main-company-listing-commercial h2.patient_outcomes').first().show();
	$('.view-main-company-listing-commercial h2.selling_accelerators').first().show();
	$('.view-main-company-listing-commercial h2.selling_aasolutions').first().show();

});
;
jQuery(document).ready( google_analytics_documentready );

function google_analytics_documentready ($)
{
	$('a[target=_blank]').unbind('click.google_analytics_trackoutbound');
        $('a[target=_blank]').bind('click.google_analytics_trackoutbound', google_analytics_trackoutbound );
}


function google_analytics_trackoutbound (e)
{       
	try     
	{       
		_gaq.push(["_trackEvent", "Outbound links", "Click", e.target.href]);
	}       
	catch(err)
	{       
	}       
	return true;
}
;
/*!
 * SwipeView v0.10 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
 * Released under MIT license, http://cubiq.org/license
 */
var SwipeView = (function(){
	var hasTouch = 'ontouchstart' in window,
		resizeEvent = 'onorientationchange' in window ? 'orientationchange' : 'resize',
		startEvent = hasTouch ? 'touchstart' : 'mousedown',
		moveEvent = hasTouch ? 'touchmove' : 'mousemove',
		endEvent = hasTouch ? 'touchend' : 'mouseup',
		cancelEvent = hasTouch ? 'touchcancel' : 'mouseup',
		
		SwipeView = function (el, options) {
			var i,
				div,
				className,
				pageIndex;
			var self = this;
			var callTwice = false;

			this.wrapper = typeof el == 'string' ? document.querySelector(el) : el;
			this.options = {
				text: null,
				numberOfPages: 3,
				snapThreshold: null,
				hastyPageFlip: false
			}
		
			// User defined options
			for (i in options) this.options[i] = options[i];
			
			this.wrapper.style.overflow = 'hidden';
			this.wrapper.style.position = 'relative';
			this.wrapper.className = "state_0";
			
			this.masterPages = [];
			
			div = document.createElement('div');
			div.id = 'swipeview-slider';
			div.style.cssText = 'position:relative;top:0;height:100%;width:100%;-webkit-transition-duration:0;-webkit-transform:translate3d(0,0,0);-webkit-transition-timining-function:ease-out';
			this.wrapper.appendChild(div);
			this.slider = div;
			this.slider.addEventListener('webkitTransitionEnd', function(e) { self.__updateClass(); });

			this.refreshSize();

			for (i=-1; i<2; i++) {
				div = document.createElement('div');
				div.id = 'swipeview-masterpage-' + (i+1);
				div.style.cssText = '-webkit-transform:translateZ(0);position:absolute;top:0;height:100%;width:100%;left:' + i*100 + '%';
				if (!div.dataset) div.dataset = {};
				pageIndex = i == -1 ? this.options.numberOfPages - 1 : i;
				div.dataset.pageIndex = pageIndex;
				div.dataset.upcomingPageIndex = pageIndex;

				this.slider.appendChild(div);
				this.masterPages.push(div);
			}
			
			className = this.masterPages[1].className;
			this.masterPages[1].className = !className ? 'swipeview-active' : className + ' swipeview-active';

			window.addEventListener(resizeEvent, this, false);
			this.wrapper.addEventListener(startEvent, this, false);
			this.wrapper.addEventListener(moveEvent, this, false);
			this.wrapper.addEventListener(endEvent, this, false);
			this.slider.addEventListener('webkitTransitionEnd', this, false);

/*			if (!hasTouch) {
				this.wrapper.addEventListener('mouseout', this, false);
			}*/
		};
	
	SwipeView.prototype = {
		currentMasterPage: 1,
		x: 0,
		page: 0,
		pageIndex: 0,
		customEvents: [],
		
		onFlip: function (fn) {
			this.wrapper.addEventListener('swipeview-flip', fn, false);
			this.customEvents.push(['flip', fn]);
		},
		
		onMoveOut: function (fn) {
			this.wrapper.addEventListener('swipeview-moveout', fn, false);
			this.customEvents.push(['moveout', fn]);
		},

		onMoveIn: function (fn) {
			this.wrapper.addEventListener('swipeview-movein', fn, false);
			this.customEvents.push(['movein', fn]);
		},
		
		onTouchStart: function (fn) {
			this.wrapper.addEventListener('swipeview-touchstart', fn, false);
			this.customEvents.push(['touchstart', fn]);
		},

		destroy: function () {
			var i, l;
			for (i=0, l=customEvents.length; i<l; i++) {
				this.wrapper.removeEventListener('swipeview-' + this.customEvents[i][0], this.customEvents[i][1], false);
			}
			
			this.customEvents = [];
			
			// Remove the event listeners
			window.removeEventListener(resizeEvent, this, false);
			this.wrapper.removeEventListener(startEvent, this, false);
			this.wrapper.removeEventListener(moveEvent, this, false);
			this.wrapper.removeEventListener(endEvent, this, false);
			this.slider.removeEventListener('webkitTransitionEnd', this, false);

/*			if (!hasTouch) {
				this.wrapper.removeEventListener('mouseout', this, false);
			}*/
		},

		refreshSize: function () {
			this.wrapperWidth = this.wrapper.clientWidth;
			this.wrapperHeight = this.wrapper.clientHeight;
			this.pageWidth = this.wrapperWidth;
			this.maxX = -2 * this.pageWidth + this.wrapperWidth;
			this.snapThreshold = this.options.snapThreshold === null
				? Math.round(this.pageWidth * .15)
				: /%/.test(this.options.snapThreshold)
					? Math.round(this.pageWidth * this.options.snapThreshold.replace('%', '') / 100)
					: this.options.snapThreshold;
		},
		
		updatePageCount: function (n) {
			this.options.numberOfPages = n;
		},
		
		goToPage: function (p) {
			var i;

			this.masterPages[this.currentMasterPage].className = this.masterPages[this.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, '');
			for (i=0; i<3; i++) {
				className = this.masterPages[i].className;
				/(^|\s)swipeview-loading(\s|$)/.test(className) || (this.masterPages[i].className = !className ? 'swipeview-loading' : className + ' swipeview-loading');
			}
			
			p = p < 0 ? 0 : p > this.options.numberOfPages-1 ? this.options.numberOfPages-1 : p;
			this.page = p;
			this.pageIndex = p;
			this.slider.style.webkitTransitionDuration = '0';
			this.__pos(-p * this.pageWidth);

			this.currentMasterPage = (this.page + 1) - Math.floor((this.page + 1) / 3) * 3;

			this.masterPages[this.currentMasterPage].className = this.masterPages[this.currentMasterPage].className + ' swipeview-active';

			if (this.currentMasterPage == 0) {
				this.masterPages[2].style.left = this.page * 100 - 100 + '%';
				this.masterPages[0].style.left = this.page * 100 + '%';
				this.masterPages[1].style.left = this.page * 100 + 100 + '%';
				
				this.masterPages[2].dataset.upcomingPageIndex = this.page == 0 ? this.options.numberOfPages-1 : this.page - 1;
				this.masterPages[0].dataset.upcomingPageIndex = this.page;
				this.masterPages[1].dataset.upcomingPageIndex = this.page == this.options.numberOfPages-1 ? 0 : this.page + 1;
			} else if (this.currentMasterPage == 1) {
				this.masterPages[0].style.left = this.page * 100 - 100 + '%';
				this.masterPages[1].style.left = this.page * 100 + '%';
				this.masterPages[2].style.left = this.page * 100 + 100 + '%';

				this.masterPages[0].dataset.upcomingPageIndex = this.page == 0 ? this.options.numberOfPages-1 : this.page - 1;
				this.masterPages[1].dataset.upcomingPageIndex = this.page;
				this.masterPages[2].dataset.upcomingPageIndex = this.page == this.options.numberOfPages-1 ? 0 : this.page + 1;
			} else {
				this.masterPages[1].style.left = this.page * 100 - 100 + '%';
				this.masterPages[2].style.left = this.page * 100 + '%';
				this.masterPages[0].style.left = this.page * 100 + 100 + '%';

				this.masterPages[1].dataset.upcomingPageIndex = this.page == 0 ? this.options.numberOfPages-1 : this.page - 1;
				this.masterPages[2].dataset.upcomingPageIndex = this.page;
				this.masterPages[0].dataset.upcomingPageIndex = this.page == this.options.numberOfPages-1 ? 0 : this.page + 1;
			}
			
			this.__flip();
		},
		
		next: function () {
			this.directionX = -1;
			this.x -= 1;
			this.__checkPosition();
		},

		prev: function () {
			this.directionX = 1;
			this.x += 1;
			this.__checkPosition();
		},

		prev2: function () {
			this.callTwice = true;
			this.prev();
		},

		handleEvent: function (e) {
			switch (e.type) {
				case startEvent:
					this.__start(e);
					break;
				case moveEvent:
					this.__move(e);
					break;
				case cancelEvent:
				case endEvent:
					this.__end(e);
					break;
				case resizeEvent:
				 	this.__resize();
					break;
				case 'webkitTransitionEnd':
					if (e.target == this.slider && !this.options.hastyPageFlip) this.__flip();
					break;
			}
		},


		/**
		 *
		 * Pseudo private methods
		 *
		 */
		__pos: function (x) {
			this.x = x;
			this.slider.style.webkitTransform = 'translate3d(' + x + 'px,0,0)';
		},

		__resize: function () {
			this.refreshSize();
			this.slider.style.webkitTransitionDuration = '0';
			this.__pos(-this.page * this.pageWidth);
		},

		__start: function (e) {
			//e.preventDefault();

			if (this.initiated) return;
			
			var point = hasTouch ? e.touches[0] : e;
			
			this.initiated = true;
			this.moved = false;
			this.thresholdExceeded = false;
			this.startX = point.pageX;
			this.startY = point.pageY;
			this.pointX = point.pageX;
			this.pointY = point.pageY;
			this.stepsX = 0;
			this.stepsY = 0;
			this.directionX = 0;
			this.directionLocked = false;
			
/*			var matrix = getComputedStyle(this.slider, null).webkitTransform.replace(/[^0-9-.,]/g, '').split(',');
			this.x = matrix[4] * 1;*/

			this.slider.style.webkitTransitionDuration = '0';
			
			this.__event('touchstart');
		},
		
		__move: function (e) {
			
			clearInterval(homeInterval);
			homeInterval = setInterval("moveHomeForward()", 12000);
			
			if (!this.initiated) return;

			var point = hasTouch ? e.touches[0] : e,
				deltaX = point.pageX - this.pointX,
				deltaY = point.pageY - this.pointY,
				newX = this.x + deltaX,
				dist = Math.abs(point.pageX - this.startX);

			this.moved = true;
			this.pointX = point.pageX;
			this.pointY = point.pageY;
			this.directionX = deltaX > 0 ? 1 : deltaX < 0 ? -1 : 0;
			this.stepsX += Math.abs(deltaX);
			this.stepsY += Math.abs(deltaY);

			// We take a 10px buffer to figure out the direction of the swipe
			if (this.stepsX < 10 && this.stepsY < 10) {
//				e.preventDefault();
				return;
			}

			// We are scrolling vertically, so skip SwipeView and give the control back to the browser
			if (!this.directionLocked && this.stepsY > this.stepsX) {
				this.initiated = false;
				return;
			}

			e.preventDefault();

			this.directionLocked = true;

			if (!this.thresholdExceeded && dist >= this.snapThreshold) {
				this.thresholdExceeded = true;
				this.__event('moveout');
			} else if (this.thresholdExceeded && dist < this.snapThreshold) {
				this.thresholdExceeded = false;
				this.__event('movein');
			}
			
			this.__updateClass();
			
/*			if (newX > 0 || newX < this.maxX) {
				newX = this.x + (deltaX / 2);
			}*/

			this.__pos(newX);
		},
		
		__end: function (e) {
			if (!this.initiated) return;
			
			var point = hasTouch ? e.changedTouches[0] : e;

			this.initiated = false;
			
			if (!this.moved) return;
			
			// Check if we exceeded the snap threshold
			if (Math.abs(point.pageX - this.startX) < this.snapThreshold) {
				this.slider.style.webkitTransitionDuration = '300ms';
				this.__pos(-this.page * this.pageWidth);
				return;
			}

			this.__checkPosition();
		},
		
		__checkPosition: function () {
			var pageFlip,
				pageFlipIndex,
				className;
				
			this.masterPages[this.currentMasterPage].className = this.masterPages[this.currentMasterPage].className.replace(/(^|\s)swipeview-active(\s|$)/, '');
			
			// Flip the page
			if (this.directionX > 0) {
				// console.log("SWIPE RIGHT");
				if(this.page != 0)
					this.page = -Math.ceil(this.x / this.pageWidth);
				this.currentMasterPage = (this.page + 1) - Math.floor((this.page + 1) / 3) * 3;
				this.pageIndex = this.pageIndex == 0 ? this.options.numberOfPages - 1 : this.pageIndex - 1;

				pageFlip = this.currentMasterPage - 1;
				pageFlip = pageFlip < 0 ? 2 : pageFlip;
				this.masterPages[pageFlip].style.left = this.page * 100 - 100 + '%';

				pageFlipIndex = this.page - 1;
			} else {
				// console.log("SWIPE LEFT");
				if(this.page != this.options.numberOfPages - 1)
					this.page = -Math.floor(this.x / this.pageWidth);
				this.currentMasterPage = (this.page + 1) - Math.floor((this.page + 1) / 3) * 3;
				this.pageIndex = this.pageIndex == this.options.numberOfPages - 1 ? 0 : this.pageIndex + 1;

				pageFlip = this.currentMasterPage + 1;
				pageFlip = pageFlip > 2 ? 0 : pageFlip;
				this.masterPages[pageFlip].style.left = this.page * 100 + 100 + '%';

				pageFlipIndex = this.page + 1;
			}

			// Add active class to current page
			className = this.masterPages[this.currentMasterPage].className;
			/(^|\s)swipeview-active(\s|$)/.test(className) || (this.masterPages[this.currentMasterPage].className = !className ? 'swipeview-active' : className + ' swipeview-active');

			// Add loading class to flipped page
			className = this.masterPages[pageFlip].className;
			/(^|\s)swipeview-loading(\s|$)/.test(className) || (this.masterPages[pageFlip].className = !className ? 'swipeview-loading' : className + ' swipeview-loading');
			
			pageFlipIndex = pageFlipIndex - Math.floor(pageFlipIndex / this.options.numberOfPages) * this.options.numberOfPages;
			this.masterPages[pageFlip].dataset.upcomingPageIndex = pageFlipIndex;		// Index to be loaded in the newly flipped page

			if(this.callTwice)
				this.slider.style.webkitTransitionDuration = '250ms';
			else 
				this.slider.style.webkitTransitionDuration = '500ms';
			
			newX = -this.page * this.pageWidth;

			if (this.x == newX) {
				this.__flip();		// If we swiped all the way long to the next page (extremely rare but still)
			} else {
				this.__pos(newX);
				if (this.options.hastyPageFlip) this.__flip();
			}
		},
		
		__updateClass: function() {
			
			jQuery("#carousel").removeClass().addClass('state_'+this.page);
			
			if(this.callTwice) {
				this.callTwice = false;
				this.prev();
			}

		},
		
		__flip: function () {
			this.__event('flip');

			for (i=0; i<3; i++) {
				this.masterPages[i].className = this.masterPages[i].className.replace(/(^|\s)swipeview-loading(\s|$)/, '');		// Remove the loading class
				this.masterPages[i].dataset.pageIndex = this.masterPages[i].dataset.upcomingPageIndex;
			}

		},
		
		__event: function (type) {
			var //i,
				ev = document.createEvent("Event");
			
			ev.initEvent('swipeview-' + type, true, true);

//			for (i in parms) ev[i] = parms[i];

			this.wrapper.dispatchEvent(ev);
		}
	};

	return SwipeView;
})();;

