
// reset all iframe URLs on page load to prevent Firefox triggering unlockContent on page load
jQuery(document).ready(function() {
    jQuery('.iframeBox iframe').each(function(ix,el) {
	el.attr('src','../../images/spacer.gif');
    });
});

//var isLocalhost=false;
//try {
//    if (useDummyForms==undefined) {
//        isLocalhost=false;
//    } else if (useDummyForms==true) {
//        isLocalhost=true;
//    }
//} catch (er) {
//     useDummyForms=false;
//}
//
//if (!useDummyForms && document.domain!='localhost' && document.domain!='www.dev' && document.domain!='192.168.1.196' && document.domain!='192.168.1.176' && document.domain!='emc.sequelcommunications.com') {
//    document.domain = "emc.com";
//} else {
//    isLocalhost=true;
//}

jQuery(window).load(function() {
     
     if (jQuery('#overlayContent')) {
	nsHTML='<div id="nightShade"></div><div id="nightShadeContainer"><table id="nightShadeContainerInner" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" valign="top"><div id="nightShadeContainerInnerCollapser">';
	if (!isIE6) {
	     nsHTML+='<div id="nightShadeShadowTL"></div><div id="nightShadeShadowTC"></div><div id="nightShadeShadowTR"></div><div id="nightShadeShadowML"></div><div id="nightShadeShadowMR"></div><div id="nightShadeShadowBL"></div><div id="nightShadeShadowBC"></div><div id="nightShadeShadowBR"></div>';
	}
	nsHTML+='<div id="nightShadeContainerContent"></div><div id="nightShadeClose"><img src="overlay-apr2011/closeBtn.png" width="30" height="24" border="0" /></div><div class="clearBothTight"></div></div><div class="clearBothTight"></div></td></tr></table></div>';
jQuery('#content').prepend(nsHTML);

	jQuery('#nightShadeContainerContent').html(jQuery('#overlayContent').html());
	jQuery('#overlayContent').remove();
	Cufon.refresh();
	jQuery('#nightShade').click(overlayRemove);
	jQuery('#nightShadeClose').click(overlayRemove);
	jQuery('#nightShadeContainer').click(overlayRemoveWrapper);
	jQuery('#nightShade').css({opacity:0});
	jQuery('#nightShadeContainer').css({opacity:0});
        
	if (isIE6) { // needed for ie6 only
	     jQuery('#nightShade').css({position:'absolute'});
	     jQuery('#nightShadeContainer').css({position:'absolute'});
	     jQuery(window).bind('resize',nightShadeUpdate);
	     jQuery(window).bind('scroll',nightShadeUpdate);
	     nightShadeUpdate();
	}
	if (DetectAppleMobile()) {
	     jQuery('#nightShade').css({position:'absolute'});
	     jQuery('#nightShadeContainer').css({position:'absolute'});
	     setInterval(nightShadeUpdate,50);
	}
     
          if (isIE7or8) {
               var fixList=['nightShadeShadowTL',
                            'nightShadeShadowTC',
                            'nightShadeShadowTR',
                            'nightShadeShadowML',
                            'nightShadeShadowMR',
                            'nightShadeShadowBL',
                            'nightShadeShadowBC',
                            'nightShadeShadowBR'
                            ];
               for (i=0;i<fixList.length;i++) {
                    var temp=jQuery('#'+fixList[i]).css('background-image');
                    temp=temp.replace('url("','');
                    temp=temp.replace('")','');
                    jQuery('#'+fixList[i]).css({backgroundImage:'none'});
                    var filterString='progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+temp+'", sizingMethod="crop", enabled="true");';
                    jQuery('#'+fixList[i]).css({filter:filterString});
               }
          }
          
	  if (isIE6) {
             DD_belatedPNG.fix('.pngFixRule2,#nightShadeClose img');
          }
          
          //setup overlay links
          jQuery('.overlayLink').each(function(ix,el) {
               jQuery(el).click(function(ev) {
                    var evEl=jQuery(ev.target).closest('a');
                  //remove OVERLAY: from HREF, in the future this can be checked to allow different triggers or alternate setups
                    if (jQuery('nightShade')) {
                     openOverlay(jQuery(evEl).attr('overlay'));
                  }
                    ev.preventDefault();
               });
          })
          
          //play video again links
          jQuery('.playVideoAgain').each(function(ix,el) {
             jQuery(el).click(function(ev) {
                  doVideo(cOverlay);
             });
          });
     
     }

});

function loadjscssfile(filename, filetype) {
     if (filetype=="js"){ //if filename is a external JavaScript file
          var fileref=document.createElement('script');
          fileref.setAttribute("type","text/javascript");
          fileref.setAttribute("src", filename);
     } else if (filetype=="css"){ //if filename is an external CSS file
          var fileref=document.createElement("link");
          fileref.setAttribute("rel", "stylesheet");
          fileref.setAttribute("type", "text/css");
          fileref.setAttribute("href", filename);
     }
     if (typeof fileref!="undefined") {
          document.getElementsByTagName("head")[0].appendChild(fileref);
     }
}

loadjscssfile('overlay-apr2011/overlay.css','css');

/* NIGHTSHADE/OVERLAY SCRIPTS */

var hasOpenedAnOverlay=false; // for tracking whether an overlay has been opened, used to prevent Firefox unlocking content after a reload

var cOverlay='';
var overlayIsOpen=false;
function openOverlay(which) {

    if (jQuery('#nightShade')) {

	//run overlay's UNinit func if registered
	if (overlayUnInitFuncs[cOverlay]) {
	    overlayUnInitFuncs[cOverlay].call();
	}

	/* FIX PNGS in IE6 */
	if (isIE6) {
	     DD_belatedPNG.fix('.pngFixRule2,#nightShadeClose img');
	}

	hasOpenedAnOverlay=true;
	if (cOverlay=='') {
	    jQuery('#nightShade').css({opacity:0});
	    jQuery('#nightShadeContainer').css({opacity:0});
	}
	if (cOverlay!=which) {
	     cOverlay=which;
	     jQuery('.overlayPage').each(function(ix,el) {
	         if (jQuery(el).attr('id')==which) {
		     jQuery(el).css({display:'block'});
		     jQuery(el).css({visibility:'visible'});
	         } else {
		     jQuery(el).css({display:'none'});
		     jQuery(el).css({visibility:'hidden'});
	         }
	     });

	}
	
	// do actual overlay opening or bypass straight to download
	// swap comments to block auto-opening download assets when following next asset links
	if (!overlayIsOpen && jQuery('#'+cOverlay).hasClass('download') && (jQuery('#'+cOverlay).find('.form').length==0 || formAlreadySubmitted)) {
	//if (jQuery('#'+cOverlay).hasClassName('download') && (jQuery('#'+cOverlay).select('.form').length==0 || formAlreadySubmitted)) {
	     
	     //doesn't need overlay, skip straight to download file
	     var dlURL=jQuery('#'+cOverlay).find('.downloadLink').first().attr('href');
	     if (dlURL.indexOf('.pdf')>=0) {
		window.open(dlURL);
	     } else {
		window.location=dlURL;
	     }
	     //overlayRemove();
	     
	} else {

	     //needs overlay shown
	     
	     overlayIsOpen=true;
	     jQuery('#nightShade').css({display:'block'});
	     jQuery('#nightShadeContainer').css({display:'block'});
             
             jQuery('#nightShade').animate({
               opacity: 0.6,
               framerate: 30
             },600);
             jQuery('#nightShadeContainer').animate({
               opacity: 1,
               framerate: 30
             },600);
             
	     //setup and initialize content post-overlay opening
     
	     //do video for video overlays if registered and either not protected or form already submitted
	     if (jQuery('#'+cOverlay).hasClass('video') && (jQuery('#'+cOverlay).find('.form').length==0 || formAlreadySubmitted)) {
		 doVideo(jQuery('#'+cOverlay));
	     }
     
	     // hide close button on apple devices if video overlay (iOS blocks clickabilty in this case)
	     if (jQuery('#'+cOverlay).hasClass('video') && DetectAppleMobile()) {
		    jQuery('#nightShadeClose').css({display:'none'});
	     } else {
		    jQuery('#nightShadeClose').css({display:'block'});
	     }
	      	      
	}

	//run overlay's init func if registered and either not protected or form already submitted
	try {
	    if (overlayInitFuncs[cOverlay] && (jQuery('#'+cOverlay).find('.form').length==0 || formAlreadySubmitted)) {
	       overlayInitFuncs[cOverlay].call();
	    }
	} catch (err) {
	    // do nothing, just here to avoid errors on init func preventing overlay opening
	}
		

    }
    
}

function overlayRemove() {
     
     if (cOverlay!='') {
	overlayIsOpen=false;
	//run overlay's UNinit func if registered
	try {
	    if (overlayUnInitFuncs[cOverlay]) {
	       overlayUnInitFuncs[cOverlay].call();
	    }
	} catch (err) {
	    //do nothing, just here to avoid errors on uninit func preventing overlay closure
	}
	if (jQuery('#'+cOverlay).hasClass('video') && jQuery('#'+cOverlay).find('.videoTarget').length) {
	    if (modExp) { modExp.unload(); }
	}
         cOverlay='';
         
         
             jQuery('#nightShade').animate({
               opacity: 0,
               framerate: 30
             },600);
             jQuery('#nightShadeContainer').animate({
               opacity: 0,
               framerate: 30
             },600,function() {
                    jQuery('#nightShade').css({display:'none'});
                    jQuery('#nightShadeContainer').css({display:'none'});
                    jQuery('#nightShade').css({filter:''});
                    jQuery('#nightShadeContainer').css({filter:''});
                    jQuery('.overlayPage').each(function(ix,el) {
                        jQuery(el).css({display:'none'});
                    });
                });

     }
}
function overlayRemoveWrapper(ev) {
    if (jQuery(ev.target).attr('id')=='nightShadeContainer') {
	overlayRemove();
	ev.preventDefault();
    }
}
function nightShadeUpdate() { // needed for ie6 and iOS only
     if (DetectAppleMobile()) {
	//iOS
	jQuery('#nightShade').css({width:document.viewport.getWidth()+'px'});
	jQuery('#nightShade').css({height:document.viewport.getHeight()+'px'});
	//jQuery('nightShade').style.height=(jQuery('content').cumulativeOffset().top+jQuery('content').getHeight())+'px';
	jQuery('#nightShadeContainer').css({top:jQuery(document.viewport.getScrollOffsets().top)+'px'});
	jQuery('#nightShadeContainer').css({height:jQuery(document.viewport).getHeight()+'px'});
     } else {
	//ie6
	winSize={};
	winSize.width = document.documentElement.clientWidth;
	winSize.height = jQuery(document.body).height();//documentElement.clientHeight;
	if (jQuery('#nightShade') ) {
	     jQuery('#nightShade').css({width:winSize.width+'px'});
	     jQuery('#nightShade').css({height:(winSize.height)+'px'});
	     jQuery('#nightShade').css({top:(jQuery(document).scrollTop()-100)+'px'});
	     jQuery('#nightShadeContainer').css({top:jQuery(document).scrollTop()-50+'px'});
	     //jQuery('#nightShade').css({top:(document.viewport.getScrollOffsets().top-50)+'px'});
	     //jQuery('#nightShadeContainer').css({top:document.viewport.getScrollOffsets().top+'px'});
	     jQuery('#nightShadeContainer').css({width:Math.max(1000,winSize.width)+'px'});
	     jQuery('#nightShadeContainer').css({height:(winSize.height)+'px'});
	     pageFix=jQuery(document.body).offset();
	     jQuery('#nightShade').css({left:(0-pageFix.left)+'px'});
	     jQuery('#nightShadeContainer').css({position:'absolute'});
	     jQuery('#nightShadeContainer').css({left:(0-pageFix.left)+'px'});
	}
     }
}


function resizeIframe() { /* DOES NOTHING, JUST HERE TO PREVENT JS ERRORS */ }

var formAlreadySubmitted=false;
var userEmail=false;
var preFormSubmitted=false;
var hasOpenedAnOverlay=false;
function contactSubmitted(inEmail) {
    unlockContent(inEmail); //pass-through so either function works
}
function unlockContent(inEmail) {
    if (hasOpenedAnOverlay) { //prevents Firefox trying to unlock content on a reload since it doesn't reset iframe URLs
        preFormSubmitted=true;
        userEmail=inEmail;
        formAlreadySubmitted=true;
        jQuery('#'+cOverlay).find('.iframeElement').css({display:'none'});
        jQuery('.showAfterUnlock').each(function(ix,el) { jQuery(el).css({display:'block'}); });
        //insert email into URLS
        jQuery('a.addEmailLinks').each(function(ix,el){
            el.href=el.href.split('[[EMAIL]]').join(inEmail);
        });
        jQuery('.iframeURLpost.addEmailLinks').each(function(ix,el){
            jQuery(el).html(el.innerHTML.split('[[EMAIL]]').join(inEmail));
        });
        // hide "to download" text
        jQuery('.hideAfterUnlock').each(function(ix,el) {
            //el.style.visibility='hidden';
            jQuery(el).css({display:'none'});
        });
        //play video if appropriate
        if (jQuery('#'+cOverlay).hasClass('video')) {
              doVideo(jQuery('#'+cOverlay));
        }
	//run overlay's init func if registered
	try {
	    if (overlayInitFuncs[cOverlay]) {
	       overlayInitFuncs[cOverlay].call();
	    }
	} catch (err) {
	    //do nothing, just here to avoid errors on init func preventing overlay opening
	}

    }
}


/* VIDEOPLAYER SUPPORT */
//dynamically load and add brightcove JS files
loadjscssfile("http://admin.brightcove.com/js/BrightcoveExperiences.js", "js");
loadjscssfile("http://admin.brightcove.com/js/APIModules_all.js", "js");
var overlayHTML='';
var bcInterval;
function doVideo(el) {
     if (el!=undefined) {
          overlayHTML = '<object id="emcExperience" class="BrightcoveExperience">' +
               '<param name="bgcolor" value="#000000" />';
	     
          //JUST USE PIXEL SETTINGS FOR ALL SINCE SAFARI 5 ALSO DIDN'T LIKE 100%
          overlayHTML += '<param name="width" value="'+jQuery('#'+cOverlay).width()+'" /><param name="height" value="'+jQuery('#'+cOverlay).height()+'" />';
	     
          overlayHTML += '<param name="isVid" value="true" />' +
               '<param name="isUI" value="true" />' +
               '<param name="autoStart" value="true" />' +
               '<param name="dynamicStreaming" value="true" />' +
               '<param name="templateErrorHandler" value="onPlayerError" />' +
               '<param name="wmode" value="transparent" />' +

               //'<param name="dsUser" value="gpogpo" />' +
               //'<param name="dsMulti" value="false" />' +

               '<param name="playerID" value="949252753001" />' +
               '<param name="playerKey" value="AQ~~,AAAAoc2nJVE~,yIQzUe15OpLcz7KPrk2AqKId2oggWw7T" />' +
               //'<param name="playerID" value="732388579001" />' +
               //'<param name="playerKey" value="AQ~~,AAAAoc2nJVE~,yIQzUe15OpL5IwZXku0pp8S76mf6ISAk" />' +
	       //remove "BC:" from video ID, in the future this can be checked to allow for different video source, IE "YT:" for YouTube, etc.
		
	       '<param name="@videoPlayer" value="'+el.find('.videoID').first().html().replace('BC:','').replace('bc:','').replace('Bc:','')+'" />' +

               '</object>';
          if (overlayHTML!='') {
               if (jQuery('#'+cOverlay).find('.videoTarget').length) {
                    jQuery('#'+cOverlay).find('.videoTarget').first().html();
               }
               jQuery('#'+cOverlay).append('<div class="videoTarget">'+overlayHTML+'</div>');
               bcInterval=setInterval(function(){
                    try {
                         if (brightcove) {
                              brightcove.createExperiences();
                              clearInterval(bcInterval);
                         }
                    } catch(err) {
                         //brightcove scripts not loaded yet, do nothing
                    }
               },50);
          }
     }
}


// BRIGHTCOVE SUPPORT
var modVP;
var bcExp;
var modExp;
var modControls;
function onTemplateLoaded(experienceID) {
	try {
		bcExp = brightcove.getExperience(experienceID);
		modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
		modExp = bcExp.getModule(APIModules.EXPERIENCE);
		modVP.addEventListener('mediaProgress', checkVidProgress );
	} catch(err) {}
}

function onPlayerError(ev) {
	//do nothing
}

function checkVidProgress(ev) {
    var perc=ev.position/modVP.getVideoDuration();
    if (perc>0.999) {
	//remove VP at end if there is "showAfterUnlock" content, returning user to overlay which shows new content, otherwise remain in place
	jQuery('#'+cOverlay).find('.showAfterUnlock').css({display:'block'});
	// kill and remove VP
	if (modExp) { modExp.unload(); }
	jQuery('#'+cOverlay).find('.videoTarget').remove();
    }
}


/* MOBILE BROWSER DETECTION KIT */
var deviceIphone = "iphone";
var deviceIpod = "ipod";
var deviceIpad = "ipad";
var deviceAndroid = "android";
var engineWebKit = "webkit";

//Initialize our user agent string to lower case.
var uagent = navigator.userAgent.toLowerCase();

// Detects if the current device is an iPhone.
function DetectIphone() {
   if (uagent.search(deviceIphone) > -1)
      return true;
   else
      return false;
}

// Detects if the current device is an iPad.
function DetectIpad() {
   if (uagent.search(deviceIpad) > -1)
      return true;
   else
      return false;
}

// Detects if the current device is an iPod Touch.
function DetectIpod() {
   if (uagent.search(deviceIpod) > -1)
      return true;
   else
      return false;
}

function DetectAppleMobile() {
    return DetectIpod() || DetectIpad() || DetectIphone();
}

// Detects if the current device is an Android OS-based device.
function DetectAndroid() {
   if (uagent.search(deviceAndroid) > -1)
      return true;
   else
      return false;
}

// Detects if the current device is an Android OS-based device and the browser is based on WebKit.
function DetectAndroidWebKit() {
   if (DetectAndroid()) {     if (uagent.search(engineWebKit) > -1)
        return true;
     else
        return false;
   }
   else
      return false;
}

function detectSmartPhone() {
    return DetectAppleMobile() || DetectAndroidWebKit() ;
}

var overlayInitFuncs={};
function registerOverlayInitScript(overlayName,func) {
     overlayInitFuncs[overlayName]=func;
}
var overlayUnInitFuncs={};
function registerOverlayUnInitScript(overlayName,func) {
     overlayUnInitFuncs[overlayName]=func;
}
