// Document.domain set so that third party sites like Resumeware and Thompson Reuters
//  Email (pop-iframe) close and submit functions do not get Permission Denied
//  Checking that we are not on the cm.domain.com environment because this causes issues in Preview (Ribbon)
//alert(' location.host ' + location.host.substring(3, 0 ));

// Limit to sjm.com so that careers.sjm.com and investors.sjm.com 
//      Email popup overlay close/cancel buttons do not give "Permission Denied" or "Access is denied" errors.
//      Remove search page, too since Coveo 6.2 Access Denied
if ((location.host != "localhost") && (location.host.substring(3, 0) != "cm.") &&
     (location.host.toLowerCase().match(".sjm.com")) &&
     !(location.host.toLowerCase().match("health.sjm.com")) &&
     !(location.pathname.toLowerCase().match("search.aspx"))) {
    // This did not work because all pages need to set document.domain on our side and on the third party side, including Coveo
    // Idea:  Limit this to careers.sjm.com and investors.sjm.com and our Email.aspx page called by them to avoid additional issues like 
    // with Coveo 6.1 in IE6 and IE7 with "Access Denied"
    //alert('location pathname ' + location.pathname + ' lower ' + location.pathname.toLowerCase() + ' ' + location.pathname.toLowerCase().match("email.aspx"));
    //if ( (location.host.substring(8,0) == "careers.") || (location.host.substring(10,0) == "investors.") || (location.pathname.toLowerCase().match("email.aspx") ) )
    //{
    var locationDomainParts = location.host.split('.');
    //window.document.domain = "sjm.com";
    if (locationDomainParts.length > 2) {
        //alert(' document.domain Parts > 2' + locationDomainParts[locationDomainParts.length - 2] + '.' + locationDomainParts[locationDomainParts.length - 1]);
        window.document.domain = locationDomainParts[locationDomainParts.length - 2] + '.' + locationDomainParts[locationDomainParts.length - 1];
    } else {
        //alert(' document.domain Parts <= 2' + locationDomainParts[0] + ' Ct ' + locationDomainParts.length);
        window.document.domain = locationDomainParts[0] + '.' + locationDomainParts[1];
    }
    //alert('document.domain ' + window.document.domain);
    //}
}

// avoid prototype.js collisions
$jq = jQuery.noConflict();

// variable configurations
var animspeed = 'normal';
var d = new Date; // used for assigning dynamic IDs to page elements
var flowplayerSwf = "/layouts/SJMSites/_swf/flowplayer.commercial-3.2.7.swf";
var flowplayerGASwf = "/layouts/SJMSites/_swf/flowplayer.analytics-3.2.2.swf";

// determine and assign correct key to use for flowplayer
var fp_keys = { // all registered keys
    "sjm.com": "#@3bdc57988152bcaed8a",
    "*.sjm.com": "#@3bdc57988152bcaed8a",
    "sjmprofessional.com": "#@a34e1a89ee81868efc4",
    "*.sjmprofessional.com": "#@a34e1a89ee81868efc4",
    "heartvalveanswers.com": "#@dcb8d244d730a433663",
    "*.heartvalveanswers.com": "#@dcb8d244d730a433663",
    "sjmneuropro.com": "#@bd9cfb28df715328d68",
    "*.sjmneuropro.com": "#@bd9cfb28df715328d68"
};

var hostkey = '';
var hostname = location.host;
var arr_mask = hostname.split('.');
if (arr_mask.length > 2) {
    hostkey = '*.';
    hostkey += arr_mask[arr_mask.length - 2] + '.';
    hostkey += arr_mask[arr_mask.length - 1];
} else {
    hostkey = arr_mask[0] + '.' + arr_mask[1];
}

var fp_key = fp_keys[hostkey];
// Setting to a default for testing environments
if (!fp_key) {
    fp_key = '#@3bdc57988152bcaed8a';
}

// utility function for calling from inside popup iframes
// use self.parent.closeOverlay() inside an iframe to close 
// the overlay structure
function closeOverlay() {
    $jq('#js-content').trigger('click');
}

// Utility to get a querystring parameter (used in pop-iframe window size)
function getParameterByName(name, theUrl) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(theUrl);

    //alert('getParameterByName name ' + name + ' theUrl ' + theUrl);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

$jq(function() {

    // popup displays
    $jq('body').append('<div id="js-overlay"><\/div><div id="js-content"></\div>');
    $jq('#js-content').livequery(
		'click',
		function() {
		    $jq('#js-content').fadeOut(animspeed);
		    $jq('#js-overlay').fadeOut(
				animspeed,
				function() {
				    $jq('html').removeClass('overlay-active');
				    /*
				    to get things to work in ie6 we need to completely
				    destroy and rebuild these elements
				    */
				    $jq('div#js-overlay').remove();
				    $jq('div#js-content').remove();
				    $jq('body').append('<div id="js-overlay"><\/div><div id="js-content"></\div>')
				}
			);
		}
	);
    $jq('#js-content table.overlay-content').livequery(
		'click',
		function(e) { e.stopPropagation(); }
	);

    // 04/22/10 Marcia - this was causing “Stop running this script” error under IE (6,7,8) on third party sites like Thomson Reuters
    //     http://investors.sjm.com/phoenix.zhtml?c=73836&p=irol-news 
    //// popup failsafe
    //$jq('*[class^="pop-"]:not("a")').each(function(){
    //	var thetype = $jq(this).attr('class');
    //	$jq(this).parents('a').addClass(thetype);
    //});


    // popup: video
    $jq('a.pop-video').livequery(
		'click',
		function() {

		    var theRandomNumber = d.getTime();
		    //var theRandomNumber = 3;
		    var theURL = $jq(this).attr('href');
		    $jq('#js-content').append(
				'<table class="overlay-wrapper overlay-wrapper-close" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
					'<table class="overlay-content" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
						'<a class="popup-video" id="vid' + theRandomNumber + '" href="' + theURL + '"></a>' +
					'<\/td><\/tr><\/table>' +
				'<\/td><\/tr><\/table>'
			);
		    //alert('pop-video'+fp_key);
		    $jq('#vid' + theRandomNumber).flowplayer(flowplayerSwf, {
		        clip: {
		            onStart: function(clip) {
		                $jq(this.getParent()).css(
								{
								    width: clip.metaData.width,
								    height: clip.metaData.height
								}
							);
		            } // more config vars can go here
                },
                // Set Play Button Image     
                play: {
                    url: '/layouts/SJMSites/_images/video_icon_227px.png',
                    width: 227,
                    height: 129
                },
		        key: fp_key,
		        plugins: {
		            gatracker: {
		                url: flowplayerGASwf,
		                events: {
		                    all: true,
		                    finish: 'Finish'
		                },
		                accountId: trackerId    // trackerId set in calling layout
		            }
		        }
		    });
		    
		    $jq('html').addClass('overlay-active');
		    $jq('#js-overlay').fadeIn(animspeed);
		    $jq('#js-content').fadeIn(animspeed);
		    return false;
		}
	);
    // popup: image
    $jq('a.pop-image').livequery(
		'click',
		function() {
		    var theURL = $jq(this).attr('href');
		    $jq('#js-content').append(
				'<table class="overlay-wrapper" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
					'<table class="overlay-content" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
					'<\/td><\/tr><\/table>' +
				'<\/td><\/tr><\/table>'
			);
		    $jq('table.overlay-content td:first').load(
				theURL,
				function() {
				    $jq('html').addClass('overlay-active');
				    $jq('#js-overlay').fadeIn(animspeed);
				    $jq('#js-content').fadeIn(animspeed);
				}
			);
		    return false;
		}
	);

    // popup: iframe/form
    $jq('#signup a').addClass('pop-iframe');
    $jq('a.pop-iframe').livequery(
		'click',
		function() {
		    var showClose = '';
		    var theURL = $jq(this).attr('href');
		    // Adding an option to pass the iframe window size to handle cases such as the Premere product
		    // Syntax:  <a href="" class="pop-iframe" windowX="XXX" windowY="YYY">description</a>
		    var theWidth = $jq(this).attr('windowX');
		    if (theWidth == undefined) {
		        theWidth = getParameterByName('windowX', theURL);
		        if (theWidth == '') {
		            // default width
		            theWidth = 710;
		        }
		        else {
		            // Found a querystring parameter windowX
		            //      Not showing close unless we have a querystring showClose=1 if using querystrings
		            //      showClose = ' overlay-wrapper-close ';
		            var doShowClose = getParameterByName('showClose', theURL);
		            if (doShowClose == '1') {
		                showClose = ' overlay-wrapper-close ';
		            }
		        }
		    }
		    else {
		        showClose = ' overlay-wrapper-close ';
		    }

		    var theHeight = $jq(this).attr('windowY');
		    if (theHeight == undefined) {
		        theHeight = getParameterByName('windowY', theURL);
		        if (theHeight == '') {
		            // default height
		            theHeight = 450;
		        }
		    }
		    //alert('params' + theURL + ' W:' + theWidth + ' H:' + theHeight);
		    //'<iframe src="' + theURL + '" width="710" height="450" frameborder="0"><\/iframe>' +
		    $jq('#js-content').append(
				'<table class="overlay-wrapper ' + showClose + '" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
					'<table class="overlay-content" cellspacing="0" cellpadding="0" border="0"><tr><td>' +
						'<iframe src="' + theURL + '" width="' + theWidth + '" height="' + theHeight + '" frameborder="0"><\/iframe>' +
					'<\/td><\/tr><\/table>' +
				'<\/td><\/tr><\/table>'
			);
		    $jq('html').addClass('overlay-active');
		    $jq('#js-overlay').fadeIn(animspeed);
		    $jq('#js-content').fadeIn(animspeed);
		    return false;
		}
	);

    // popup: closer boxes
    $jq('.closer img').livequery(
		'click',
		function() {
		    //$jq('#js-content').trigger('click');
		    //alert('close');
		    self.parent.closeOverlay();
		}
	);

    // Left Navigation Video Promo
    $jq('a#player_left_nav').livequery(
		'click',
		function() {
		    var theURL = $jq(this).attr('href');
		    trackIt('/VideoPromo/' + theURL, false, true);
		}
    );

    $jq("#player_left_nav").flowplayer(flowplayerSwf, {
        key: fp_key,
        clip: {
            autoPlay: true,
            autoBuffering: true
        },
        // Set Play Button Image     
        play: {
            url: '/layouts/SJMSites/_images/video_icon_227px.png',
            width: 227,
            height: 129
        },
        plugins: {
            controls: null, // disable default controls
            gatracker: {
                url: flowplayerGASwf,
                events: {
                    all: true,
                    finish: 'Finish'
                },
                accountId: trackerId    // trackerId set in calling layout
            }
        }

    });

    // Left Navigation Video Promo One
    $jq('a#player_left_nav_1').livequery(
		    'click',
		    function() {
		        var theURL = $jq(this).attr('href');
		        trackIt('/VideoPromo/' + theURL, false, true);
		    }
        );

    $jq("#player_left_nav_1").flowplayer(flowplayerSwf, {
        key: fp_key,
        clip: {
            autoPlay: true,
            autoBuffering: true
        },
        // Set Play Button Image     
        play: {
            url: '/layouts/SJMSites/_images/video_icon_227px.png',
            width: 227,
            height: 129
        },
        plugins: {
            controls: null, // disable default controls
            gatracker: {
                url: flowplayerGASwf,
                events: {
                    all: true,
                    finish: 'Finish'
                },
                accountId: trackerId    // trackerId set in calling layout
            }
        }
    });

    // Left Navigation Video Promo One
    $jq('a#player_left_nav_2').livequery(
		    'click',
		    function() {
		        var theURL = $jq(this).attr('href');
		        trackIt('/VideoPromo/' + theURL, false, true);
		    }
        );

    $jq("#player_left_nav_2").flowplayer(flowplayerSwf, {
        key: fp_key,
        clip: {
            autoPlay: true,
            autoBuffering: true
        },
        // Set Play Button Image     
        play: {
            url: '/layouts/SJMSites/_images/video_icon_227px.png',
            width: 227,
            height: 129
        },
        plugins: {
            controls: null, // disable default controls
            gatracker: {
                url: flowplayerGASwf,
                events: {
                    all: true,
                    finish: 'Finish'
                },
                accountId: trackerId    // trackerId set in calling layout
            }
        }

    });

    // Left Navigation Video Promo One
    $jq('a#player_left_nav_3').livequery(
		    'click',
		    function() {
		        var theURL = $jq(this).attr('href');
		        trackIt('/VideoPromo/' + theURL, false, true);
		    }
        );

    $jq("#player_left_nav_3").flowplayer(flowplayerSwf, {
        key: fp_key,
        clip: {
            autoPlay: true,
            autoBuffering: true
        },
        // Set Play Button Image     
        play: {
            url: '/layouts/SJMSites/_images/video_icon_227px.png',
            width: 227,
            height: 129
        },
        plugins: {
            controls: null, // disable default controls
            gatracker: {
                url: flowplayerGASwf,
                events: {
                    all: true,
                    finish: 'Finish'
                },
                accountId: trackerId    // trackerId set in calling layout
            }
        }

    });

    // Video Player and Menu on page wherever 
    $jq('a.video_player_clip').livequery(
		'click',
		function() {
		    var theURL = $jq(this).attr('href');

		    // Remove current from rest			
		    $jq("a.video_player_clip").removeClass('current');

		    // Set the class to current
		    $jq(this).addClass('current');

		    //alert('video_player_clip '+theURL+' trackerId '+trackerId);
		    //$jq('#video_player').flowplayer( flowplayerSwf, theURL);

		    // Had to do this twice so first video would play - need to figure out why, but leaving it for now
		    $jq('#video_player').flowplayer(flowplayerSwf, {
		        key: fp_key,
		        clip: {
		            url: theURL,
		            autoPlay: true,
		            autoBuffering: true
		        },
		        // Set Play Button Image     
		        play: {
		            url: '/layouts/SJMSites/_images/video_icon_438px.png',
		            width: 438,
		            height: 247
		        },
		        plugins: {
		            gatracker: {
		                url: flowplayerGASwf,
		                events: {
		                    all: true,
		                    finish: 'Finish'
		                },
		                accountId: trackerId    // trackerId set in calling layout
		            }
		        }
		    });

		    // Track the Video
		    trackIt('/Video/' + theURL, false, true);
		    $jq('#video_player').flowplayer(flowplayerSwf, {
		        key: fp_key,
		        clip: {
		            url: theURL,
		            autoPlay: true,
		            autoBuffering: true
		        },
		        // Set Play Button Image     
		        play: {
		            url: '/layouts/SJMSites/_images/video_icon_438px.png',
		            width: 438,
		            height: 247
		        },
		        plugins: {
		            gatracker: {
		                //debug: true,
		                url: flowplayerGASwf,
		                events: {
		                    all: true,
		                    finish: 'Finish'
		                },
		                accountId: trackerId    // trackerId set in calling layout
		            }
		        }
		        //,  
		        //onBeforeFinish: function() { 
		        //    return false; 
		        //} 

		    });

		    return false;
		}
	);

    //$jq("#player").click(function(){
    //    $jq(this).parent().find("span").addClass("playing");
    //})

    //$jq("a", "#clips").each(function(){
    //    $jq(this).click(function(e){
    //	    $f().play(this.getAttribute("href", 2));
    //	    var str = $jq(this).parents("div.body").find("a:eq(1)").text();
    //	    $jq("#player").parent().find("span").addClass("playing").text(str);
    //	    e.preventDefault();
    //	    location.href="#movie-clip";
    //   });
    //});

    // Moved a.trackIt to Tracker.js

});
