// avoid prototype.js collisions
$jq = jQuery.noConflict();

/* Site Metrics functions (google analytics) and tracking and linking functions */
var trackerId = "UA-4338456-5"; 

// variable configurations
var animspeed = 'normal';
var txt_search = 'Enter Keywords';
var uri_imgpath = '/layouts/Cardiac Pro/img/';
var d = new Date; // used for assigning dynamic IDs to page elements

// 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];


// 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');
}
// SWFobject application for home page
function homepageFlash(){
	var flashvars = {
		xmlPathUS:flashXML_US,
		xmlPathIntl:flashXML_INTL
	};
	var params = {
		menu: "false",
		wmode:"transparent"
	};
	var attributes = {
		id: "hp-flash-movie",
		name: "hp-flash-movie"
	};
	swfobject.embedSWF("/layouts/Cardiac Pro/swf/Homepage.swf","hpfm","940","275","9.0.0","/layouts/Cardiac Pro/swf/expressInstall.swf",flashvars,params,attributes);
}

//Detect iPhone, iPad and iPod

function isiDevices() {
    var iFake = getQuerystring('ifake');
    if (iFake == 'true')
        return true;

    return ((navigator.userAgent.indexOf("iPad") != -1) || (navigator.userAgent.indexOf("iPhone") != -1) || (navigator.userAgent.indexOf("iPod") != -1) || (navigator.userAgent.indexOf("iTouch") != -1));
}


function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}


function getquerystring(name, url) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];

}

window.onorientationchange = function () {
    changeOverlay();
}

function changeOverlay() {
    //alert(window.orientation + " width:" + window.innerWidth + " height:" + window.innerHeight);
    //alert("js-overlay" + " width:" + $jq('#js-overlay').width() + " height:" + $jq('#js-overlay').height());

    if (window.orientation == 0) {
        $jq('#js-overlay').height(1150);
    }
    else if (window.orientation == 90) {
        $jq('#js-overlay').height(1150);
    }
    else if (window.orientation == -90) {
        $jq('#js-overlay').height(1150);
    }

}

function getFlashVersion() {
    // ie
    try {
        try {
            // avoid fp6 minor version lookup issues
            // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch (e) { return '6,0,0'; }
        } catch (e) { }
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
        // other browsers
    } catch (e) {
        try {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch (e) { }
    }
    return '0,0,0';
}


$jq(function () {
    // product image switcher
    $jq('div.img-slides .img-thumb li a').append('<span><\/span>');
    $jq('div.img-slides .img-thumb li a').bind(
		'click',
		function (x) {
		    var showNew = $jq(this).attr('class');
		    showNew = showNew.substring(0, 2);
		    var local = $jq(this).parents('div.img-slides');
		    $jq('.active', local).removeClass('active');
		    $jq(this).parents('li').addClass('active');
		    $jq('div.img-main li:visible').fadeOut(
				animspeed,
				function () {
				    $jq('#' + showNew).fadeIn(animspeed);
				}
			);
		    return false;
		}
	);

    // Expand and collapse functions moved to tabs.js

    // page tool widgets
    $jq('#printpage').bind(
		'click',
		function () {
		    window.print();
		    return false;
		}
	);
    $jq('#widgets a').bind(
		'focus',
		function () {
		    this.blur();
		}
	);
    // search form
    $jq('input.search-txt').val(txt_search);
    $jq('input.search-txt').bind(
		'focus',
		function (e) {
		    if ($jq(this).val() == txt_search) {
		        $jq(this).val('');
		    }
		}
	);
    $jq('input.search-txt').bind(
		'blur',
		function (e) {
		    if ($jq(this).val() == '') {
		        $jq(this).val(txt_search);
		    }
		}
	);
    // 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
				    */
				    // An hack to show the flash again
				    if ($jq.browser.mozilla)
				        $jq("#idflash object").show();
				    $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(); }
	);
    // 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 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>'
			);
		    $jq('#vid' + theRandomNumber).flowplayer(
				'/layouts/SJMSites/_swf/flowplayer.commercial-3.2.7.swf',
				{
				    clip: {
				        onStart: function (clip) {
				            $jq(this.getParent()).css(
								{
								    width: clip.metaData.width,
								    height: clip.metaData.height
								}
							);
				        } // more config vars can go here
				    },
				    key: fp_key,
				    plugins: {
				        gatracker: {
				            url: "/layouts/SJMSites/_swf/flowplayer.analytics-3.2.2.swf",
				            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) {
		        // default width
		        theWidth = 710;
		    }
		    else {
		        showClose = ' overlay-wrapper-close ';
		    }
		    var theHeight = $jq(this).attr('windowY');
		    if (theHeight == undefined) {
		        // default height
		        theHeight = 600;
		    }

		    if (theURL.indexOf(".mp4") != -1) {
		        showClose = '';
		    }

		    if ($jq.browser.mozilla)
		        $jq("#idflash object").hide();

		    //alert('params' + theURL + ' ' + theWidth + ' ' + 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;
		}
	);

    $jq('a.pop-iframeRequestInfo').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) {
		        // default width
		        theWidth = 710;
		    }

		    var theHeight = $jq(this).attr('windowY');
		    if (theHeight == undefined) {
		        // default height
		        theHeight = 450;
		    }

		    if (theURL.indexOf(".mp4") != -1) {
		        showClose = '';
		    }

		    if ($jq.browser.mozilla)
		        $jq("#idflash object").hide();

		    //alert('params' + theURL + ' ' + theWidth + ' ' + 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');
		}
	);

    $jq('.LightboxQualityClose').livequery(
		'click',
		function () {
		    $jq('#js-content').trigger('click');
		}
	);

    $jq('.LightboxQualityBack').livequery(
		'click',
		function () {
		    var url = $jq(this).attr("href");
		    $jq('#js-content').trigger('click');
		    $jq(location).attr('href', url);
		}
	);

    // page decoration items
    $jq('ul,ol').each(function (x) {
        $jq('li:first', this).addClass('first');
        $jq('li:last', this).addClass('last');
    });
    $jq('body').addClass('with-js');
    $jq('hr').wrap('<div class="hr"><\/div>');
    $jq('table').each(function () {
        $jq('tr:nth-child(even)', this).addClass('even');
        $jq('tr:nth-child(odd)', this).addClass('odd');
    });
    // adding flash to home page
    if ($jq('#doc.home')[0]) {
        homepageFlash();
    }
    // browser specific adjustments:
    // * Opera
    if ($jq.browser.opera) {
        $jq('ul.tabs li a').css({
            'padding': '0 5px'
        });
    }
    // neuromodulation academy popup window links
    $jq('a.nma').bind(
		'click',
		function () {
		    var popWin = window.open(
				$jq(this).attr('href'),
				'popWin',
				'menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,width=790,height=650'
			);
		    popWin.focus();
		    this.blur();
		    return false;
		}
	);

    $jq('#idswfwindow').livequery('click', function () {
        var url = ($jq(this).attr('href'));
        window.open(url, 'swfwindow', 'width=600,height=800');
        return false;

    });



});

function popUpMySizeLocation(windowname, desturl, width, height, left, top) {
    var win = window.open(desturl, windowname, 'toolbar=0,scrollbars=0,location=1,statusbar=0,menubar=0,resizable=0,width=' + width + ',height=' + height + ',left =' + left + ',top =' + top);
    win.focus();
}



