// config
var overlayOpacity=0.2;
var swfLocationRoot='/_admin/swf/pd2/'; // root-relative, start and end with a slash

// tab handling
function tabClick(which) {
    which=$(which);
    whichBodyIndex=0;
    which.up().up().select('li').each(function(e,i){
        e.removeClassName('current');
        if (which.up()==e) {whichBodyIndex=i;e.addClassName('current');}
    });
    $$('.productDetailHalfMidBody').each(function(e){e.removeClassName('showTabBody').addClassName('hideTabBody');});
    $$('.productDetailHalfMidBody')[whichBodyIndex].addClassName('showTabBody').removeClassName('hideTabBody');
}

// overlay
var isMoving=false;
function openModuleJS(newSize,time) {
    if (time==undefined) { time=1; }
    newSize=Math.ceil(newSize);
    $('overlay').style.display='block';
    $('pd2_flashModule').style.height=newSize+'px' //661+15+2 for safety
    new Effect.Opacity('overlay',{
        to: overlayOpacity,
        duration: time,
        fps: 30
    });
}
function closeModuleJS(newSize,time) {
    if (time==undefined) { time=1; }
    newSize=Math.ceil(newSize);
    new Effect.Opacity('overlay',{
        to: 0,
        duration: time,
        fps: 30,
        afterFinish: function() {
            $('overlay').style.display='none';
            $('pd2_flashModule').style.height=newSize+'px' //196+15+2 for safety
        }
    });
}
function closeModuleSWF() {
    $('pd2SWF').closeModuleSWF();
}

function overlayUpdate() { // needed for ie6 only
    winSize=document.viewport.getDimensions();
    $('overlay').style.top='0px';
    $('overlay').style.left=((winSize.width-1000)/-2)+'px';
    $('overlay').style.width=winSize.width+'px';
    $('overlay').style.height=$(document.body).getHeight()+'px';
}

try {
    if (console.log) {}    
} catch (err) {
    console={};
    console.log=function(inText){/*window.alert(inText);*/}
}
var pageURL=String(window.location.href);
var useFlash=(pageURL.indexOf('?noflash')>=0) ? false : true ;
var flashModuleTypeToLoad;
var flashModuleXMLURL;

//get URL variables
var GETS={};
var hadGets=false;
var sGet=window.location.search;
if (sGet) {
    hadGets=true;
    sGet=sGet.substr(1);
    var sNVPairs=sGet.split('&');
    for (var i=0;i<sNVPairs.length;i++) {
        var sNV=sNVPairs[i].split('=');
        GETS[sNV[0]]=sNV[1];
    }
}

Event.observe(window,'load',initPage);

var fVersion=deconcept.SWFObjectUtil.getPlayerVersion();
function initPage() {
    if (useFlash && fVersion['major']>=9) {
		if(document.getElementById('pd2_flashModulePlaceholder')) {
			document.getElementById('pd2_flashModulePlaceholder').style.dislay='none';
		}
    } else {
		if(document.getElementById('pd2_flashModulePlaceholder'))
			document.getElementById('pd2_flashModulePlaceholder').style.visibility='visible';
    }
    placeFlashModule();
}

var moduleData='';
var swfName='default';
function placeFlashModule() {

    if ($$('.overlayOpacity').length>0) {
        overlayOpacity=($$('.overlayOpacity').first().innerHTML>0 && $$('.overlayOpacity').first().innerHTML<1)?$$('.overlayOpacity').first().innerHTML:overlayOpacity;
    }
    
    dataSource=$('flashModuleSource');

    if (useFlash) {
        
        //decide whether to pull from old inline XML or new HTML-based content
        if ($('flashModuleXMLContent')) {
            //inline XML, should only ever be used by CenterStage, just here for compatibility
            moduleData=$('flashModuleXMLContent').innerHTML;
            swfName=($('flashModuleXMLContent').className=='')?'default-oldmethod':$('flashModuleXMLContent').className;
        } else {
            //HTML-based, lifted from VCE and modified
            moduleData='<pd2Data><general>';
            moduleData+='<font>'+stripBreaks(dataSource.select('.font')[0].innerHTML)+'</font>';
            moduleData+='<close>'+stripBreaks(dataSource.select('.close')[0].innerHTML)+'</close>';
            moduleData+='<modulesNavTitle>'+stripBreaks(dataSource.select('.modulesNavTitle')[0].innerHTML)+'</modulesNavTitle>';
	    moduleData+='<intro>'+stripBreaks(dataSource.select('.intro')[0].innerHTML)+'</intro>';
            if (dataSource.select('.headerLink').length>0) {
                moduleData+='<headerLink>'+stripBreaks(dataSource.select('.headerLink')[0].innerHTML)+'</headerLink>';
                moduleData+='<headerLinkContentID>'+stripBreaks(dataSource.select('.headerLinkContentID')[0].innerHTML)+'</headerLinkContentID>';
            }
            moduleData+='</general>';
            //modules
            dataSource.select('.moduleList .module').each(function(el,ix){
                var thisModule='<module>';
                el.select('div').each(function(el1,ix1){
                    thisClasses=el1.classNames();
                    thisClasses.each(function(tc){
                        if (tc!='DONOTTRANSLATE') {
                            thisModule+='<'+tc+'>';
			    if (tc=='url') {
				thisModule+=escape(stripBreaks(el.select('.'+tc)[0].innerHTML));
			    } else {
				thisModule+=stripBreaks(el.select('.'+tc)[0].innerHTML);
			    }
			    thisModule+='</'+tc+'>';
                        }
                    });
                });
                thisModule+='</module>';
                moduleData+=thisModule;
            });
            //marketing options
            dataSource.select('.moduleList .marketingoption').each(function(el,ix){
                var thisModule='<marketingoption>';
                el.select('div').each(function(el1,ix1){
                    thisClasses=el1.classNames();
                    thisClasses.each(function(tc){
                        if (tc!='DONOTTRANSLATE') {
                            thisModule+='<'+tc+'>';
			    if (tc=='url') {
				thisModule+=escape(stripBreaks(el.select('.'+tc)[0].innerHTML));
			    } else {
				thisModule+=stripBreaks(el.select('.'+tc)[0].innerHTML);
			    }
			    thisModule+='</'+tc+'>';
                        }
                    });
                });
                thisModule+='</marketingoption>';
                moduleData+=thisModule;
            });
            moduleData+='</pd2Data>';
            swfName='default';
            if (dataSource.select('.pd2swf').length>0) {
                if (dataSource.select('.pd2swf')[0].innerHTML!='') {
                    swfName=stripBreaks(dataSource.select('.pd2swf')[0].innerHTML);
                }
            }
            swfName=swfName.replace('.swf',''); //remove SWF extension if entered since script adds it anyway, this is a user error prevention
        }
        
        // set up overlay, deal with IE issues
        $(document.body).insert({top:'<div id="overlay">&nbsp;</div>'});
        if (BrowserDetect.browser=='Explorer') {
                if (BrowserDetect.version==7) { // needed for ie7 only
                        $('overlay').setOpacity(0);
                } else if (BrowserDetect.version==6) { // needed for ie6 only
                        $('overlay').style.position='absolute';
                        Event.observe(window,'resize',overlayUpdate);
                        Event.observe(window,'load',overlayUpdate);
                        overlayUpdate();
                }
        }
        Event.observe('overlay','click',closeModuleSWF);
        
        //set up flash
        posFixOffsets=$('header').cumulativeOffset();
        $(document.body).insert({top:'<div id="pd2_flashModule">&nbsp;</div>'});
        $('pd2_flashModule').makePositioned().clonePosition($('pd2_flashModulePlaceholder'),{
                setTop:true,
                setLeft:true,
                setWidth:true,
                setHeight:true,
                offsetTop:-1*posFixOffsets.top,
                offsetLeft:-1*posFixOffsets.left
        });
        var so = new SWFObject(swfLocationRoot+swfName+'.swf', 'pd2SWF', '769', '1000', '9', '#ffffff');
        so.addParam('menu', 'false');
        so.addParam('quality', 'autohigh');
        so.addParam('scale', 'noScale');
        so.addParam('wmode', 'transparent');
        so.addParam('allowfullscreen', 'true');
        so.addVariable('autoopen',(GETS.a!=undefined)?GETS.a:GETS.autoopen);
        so.addVariable('marketing',GETS.m);
        so.addVariable('xmlData',moduleData);
        so.addVariable('popupVideoRolloverText',($('popupVideoRolloverText'))?stripBreaks($('popupVideoRolloverText').innerHTML):'');
        so.addVariable('pageTitle',stripBreaks($$('.pd2_noflashTitle').first().innerHTML));
        so.addVariable('pageSubhead',stripBreaks($$('.pd2_noflashSubhead').first().innerHTML));
        so.write('pd2_flashModule');
    } else {
	if (dataSource.select('.pd2swf').length>0) {
	    if (dataSource.select('.pd2swf')[0].innerHTML!='') {
		swfName=stripBreaks(dataSource.select('.pd2swf')[0].innerHTML);
		$('pd2_flashModulePlaceholder').addClassName(swfName); // modify CSS to match new SWF modules
	    }
	}
    }
    
}

function layoutUpdateCallback(inVal) {
    inVal=Math.ceil(inVal);
    $('pd2_flashModulePlaceholder').style.height=inVal+'px';
    $('pd2_flashModule').style.height=inVal+'px';
}

function loadIframe(inURL,allowScroll,inW,inH,hOffset,vOffset,contentAreaWidth,contentAreaHeight) {
    if (allowScroll!=undefined && (allowScroll==true || allowScroll=='true' || allowScroll=='yes')) {
        allowScroll='yes';
    } else {
        allowScroll='no'
    }
    if (!$('iframeHolder')) {
        $(document.body).insert({top:'<iframe id="iframeHolder" name="iframeHolder" width="'+inW+'" height="'+inH+'" src="" frameborder="0" scrolling="'+allowScroll+'"></iframe>'});
    }
    $('iframeHolder').style.top=Number(parseInt($('pd2_flashModule').style.top)+Math.round(vOffset)+Math.round((contentAreaHeight-inH)/2))+'px';
    $('iframeHolder').style.left=Number(parseInt($('pd2_flashModule').style.left)+Math.round(hOffset)+Math.round((contentAreaWidth-inW)/2))+'px';
    setTimeout(function(){
        $('iframeHolder').src=inURL;
        $('iframeHolder').style.display='block';
    },500);
}
function unLoadIframe() {
    if ($('iframeHolder')) {
        $('iframeHolder').style.display='none';
        $('iframeHolder').remove();
    }
}

// Yahoo Pipes formatting overrides
var pipesHeight=0;
var pipesHeightShim=40; //pixels, height of Yahoo links that appear beneath scrolling area, this proved problematic to retrieve reliably during adjustment
Event.observe(window,'load',function(){if ($('pipesWrapper')) {
    var pipesUpdateCheck=setInterval(function(){
        if ($$('#pipesWrapper .ybr').length>0) {
            var ss=document.styleSheets;
            var pd2CSS=false;
            var url='';
            for(i=0;i<document.styleSheets.length;i++) {
                url=document.styleSheets[i].href;
                if (url!=null && url!=undefined) { if (url.indexOf('pd2.css')>=0) {pd2CSS=document.styleSheets[i];} }
            }
            var cssName='';
            if (BrowserDetect.browser=='Explorer') {
                pd2CSSrules=pd2CSS.rules;
            } else {
                pd2CSSrules=pd2CSS.cssRules;
            }
            for(i=0;i<pd2CSSrules.length;i++) {
                cssName=pd2CSSrules[i].selectorText;
                if (cssName=='.ybr') {
                    pipesHeight=parseInt(pd2CSSrules[i].style.height);
                }
            }
            $$('#pipesWrapper .ybr')[0].style.height=pipesHeight+'px';
            $$('#pipesWrapper div')[0].style.height=(pipesHeight+pipesHeightShim)+'px';
            $('pipesWrapper').style.height='auto'; //'show'
            if ($$('#pipesWrapper .ybr')[0].style.height==pipesHeight+'px') {
                clearInterval(pipesUpdateCheck);
            }
        }
    },100);
}});

function stripBreaks(inText) {
    return inText.split('\n').join('').split('\r').join('').strip();
}


/* PD2 copy of overlay */

var pd2overlayTime=0.5;
var pd2overlayOverlayOpacity=0.6;
var pd2overlayIsEnlarged=false;
var pd2overlayIsMoving=false;

function pd2overlayOverlayShow(which,inW,inH,inS,useDiv) {
    if (!pd2overlayIsEnlarged && !pd2overlayIsMoving && !$('pd2overlayOverlay')) {
        if (typeof(which)=='string') {
            //for direct javascript calls
            src=which;
            tW=inW;
            tH=inH;
            tS=(inS=='true'||inS=='yes')?'yes':'no';
        }
        pd2overlayIsEnlarged=true;
        $(document.body).insert({top:'<div id="pd2overlayImage"></div><div id="pd2overlayOverlay"></div>'});
        if (BrowserDetect.browser=='Explorer') {
                if (BrowserDetect.version==7) { // needed for ie7 only
                        $('pd2overlayOverlay').setOpacity(0);
                        $('pd2overlayImage').setOpacity(0);
                } else if (BrowserDetect.version==6) { // needed for ie6 only
                        $('pd2overlayOverlay').style.position='absolute';
                        $('pd2overlayImage').style.position='absolute';
                        Event.observe(window,'resize',pd2overlayOverlayUpdate);
                        Event.observe(window,'scroll',pd2overlayOverlayUpdate);
                        pd2overlayOverlayUpdate();
                }
        }
        Event.observe('pd2overlayOverlay','click',pd2overlayOverlayRemove);
        Event.observe('pd2overlayImage','click',pd2overlayOverlayRemove);
        newHTML ='<table width="100%" height="100%" cellpadding="0" cellmargin="0" border="0"><tr><td align="center" valign="middle" class="tdWithPadding">';
        newHTML+='<table cellpadding="0" cellmargin="0" border="0"><tr><td align="right" valign="top">';
        newHTML+='<div style="position: relative;">';
	newHTML+='<div class="pd2overlayClose pd2X"></div>';
	newHTML+='<div class="pd2overlayHider" style="width:'+tW+'px; height:'+tH+'px;">';
	newHTML+='<iframe width="'+tW+'" height="'+tH+'" id="pd2overlayIframeTag" name="pd2overlayIframeTag" src="'+src+'" onload="pd2overlayResizeOnLoad(this.id)" frameborder="0" scrolling="'+tS+'" />';
	newHTML+='</div>';
        newHTML+='</div>';
        newHTML+='</td></tr></table>';
        newHTML+='</td></tr></table>';
        pd2overlayIsMoving=true;
        new Effect.Opacity('pd2overlayOverlay',{
            to: pd2overlayOverlayOpacity,
            duration: 0.5,
            fps: 30,
            afterFinish: function() {
                pd2overlayIsMoving=false;
                $('pd2overlayImage').insert({top:newHTML});
            }
        });
    }
}

function pd2overlayResizeOnLoad(which) {
    $('pd2overlayOverlay').style.backgroundImage='none';
    anims=[];
    anims.push(
        new Effect.Opacity('pd2overlayImage',{
            to: 0.999,
            duration: 0.5,
            fps: 30,
            afterFinish: function(){
                $('pd2overlayImage').style.filter='';//'alpha(opacity=100)';
                $('pd2overlayImage').style.opacity=1;
                $('pd2overlayImage').select('.pd2overlayClose')[0].style.display='block';
            }
        })
    );
    new Effect.Parallel(anims,{
        duration: 0.5,
        fps: 30,
        sync: true
    });
}

function pd2overlayOverlayRemove() {
    if (pd2overlayIsEnlarged && $('pd2overlayOverlay')) {
        Event.stopObserving(window,'resize',pd2overlayOverlayUpdate);
        Event.stopObserving(window,'scroll',pd2overlayOverlayUpdate);
        pd2overlayIsEnlarged=false;
        pd2overlayIsMoving=true;
        $('pd2overlayImage').update();
        new Effect.Parallel([
            new Effect.Opacity('pd2overlayOverlay',{
                to: 0
            }),
            new Effect.Opacity('pd2overlayImage',{
                to: 0,
                afterFinish: function() {
                    $('pd2overlayOverlay').remove();
                    $('pd2overlayImage').remove();
                    pd2overlayIsMoving=false;
                }
            })
        ],{
            duration: 0.5,
            fps: 30,
            sync: true
        });
    }
}

function pd2overlayOverlayUpdate() { // needed for ie6 only
    winSize={};
    winSize.width = document.documentElement.clientWidth;
    winSize.height = document.documentElement.clientHeight;
    if ($('pd2overlayOverlay') ) {
        $('pd2overlayOverlay').style.width=winSize.width+'px';
        $('pd2overlayOverlay').style.height=(winSize.height+100)+'px';
        $('pd2overlayImage').style.width=winSize.width+'px';
        $('pd2overlayImage').style.height=(winSize.height+100)+'px';
        $('pd2overlayOverlay').style.top=(document.documentElement.scrollTop-50)+'px';
        $('pd2overlayImage').style.top=(document.documentElement.scrollTop-50)+'px';
        pageFix=document.body.cumulativeOffset();
        $('pd2overlayOverlay').style.left=(0-pageFix.left)+'px';
        $('pd2overlayImage').style.left=(0-pageFix.left)+'px';
    }
}

function pd2overlayOpen(url,width,height,allowScrolling,useDiv) {
    if (width==undefined) {width=800;}
    if (height==undefined) {height=600;}
    if (allowScrolling==undefined) {allowScrolling=false;}
    if (useDiv==undefined) {useDiv=false;}
    if (url!=undefined) {
        pd2overlayOverlayShow(url,width,height,allowScrolling,useDiv);
    }
    return false;
}

