var Gallerybp_gm;
var bp_server = "http://pixie.blogdeco.jp/";
var gallery_bp_server = bp_server;
var gallery_elSwf = null;
var gallery_sidebarswf = null;
function Gallerybp_onContent(f){
	if(!window.__ADLE){
		var n=function(){
			if(arguments.callee.d)
				return;
			arguments.callee.d=true;
			if(window.__ADLET){
				clearInterval(window.__ADLET);
				window.__ADLET=null;
			}
			for(var i=0;i<window.__ADLE.length;i++){
				window.__ADLE[i]();
			}
			window.__ADLE=null
		};
		if(document.addEventListener)document.addEventListener("DOMContentLoaded",n,false);
		// forget IE, __ie_onload defer doesnt work
		if(/WebKit/i.test(navigator.userAgent)){
			window.__ADLET=setInterval(function(){
				if(/loaded|complete/.test(document.readyState)){
					n()
				}
			},10);
		}
		window.onload=n;
		window.__ADLE=[];
	}
	window.__ADLE.push(f);
}
Gallerybp_onContent( Gallerybp_onDomLoaded );
function Gallerybp_onDomLoaded(){
	if( typeof(bp_common_loaded)!='undefined' ){
		Gallerybp.load();
	}else{
		setTimeout(Gallerybp_onDomLoaded,10);
	}
}
var Gallerybp = function(){
	// config
	var bpName			= "Gallerybp";
	var idFloatingDiv	= bpName+"_floatingDiv";
	var idFloatingSwf	= "externalInterface_"+bpName+"_floatingSwf";
	var idFloatingEmb = "externalInterface_"+bpName+"_floatingEmb";
	var idSidebarSwf  = "externalInterface_"+bpName+"_sidebarSwf";
	var idSidebarEmb  = "externalInterface_"+bpName+"_sidebarEmb";
	var elFloating;
	var swfFloating		= ["swf/Gallery.swf"];
	var swfSidebar		= "swf/Sidebar.swf";
	var lib						= "js/bp_common.js";
	var swfsize					= [600,600];
	var swfSidebarSize	= [160,120];
	var offset_top  = 0;
	var offset_left = 0;
	var aWindowSize;
	var aScrollSize;
	var aScrollPos;
	var swf_index = 0;
	var loaded = 0;		// change to 1 onload
	var b=null;	// bp_common
	var shownFromBlogparts = false;
	var active = false;	// true when showing fullscreen, false when 1x1[px]

	var params = new Object();
    var getparam = function() {
        var scripts = document.getElementsByTagName('script');
        var s = scripts[scripts.length-1];
        var pair = s.src.match(/(style|color|sidebar)=([a-zA-Z0-9,_%]*)/g);
        if ( !pair ) { return; }
        for ( var i=0; i<pair.length; i++ ) {
            var a = pair[i].split("=");
            params[a[0]] = a[1].split(",");
        }
    };
    getparam();

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;


	// sidebar
	document.write("<script type='text/javascript' charset='utf-8' src='"+gallery_bp_server+lib+"'></script>");
	if( params['sidebar']!='none' ){
        var sidebar = new SWFObject( gallery_bp_server+swfSidebar, idSidebarSwf, swfSidebarSize[0], swfSidebarSize[1], '9', '#000000' );
        sidebar.addParam('quality','high');
        sidebar.addParam('wmode','transparent');
        sidebar.addParam('allowScriptAccess','always');
        sidebar.addVariable('color',params['color']);
        document.write( sidebar.getSWFHTML() );
		cmking_ad_config = {
			partner_id  : 'ecnavi_jp_kayac_cm_kw',
			type_id     : 'KAYAC_HS_PIXIE',
			width       : 160,
			height      : 15,
			format      : 'LinkUnit',
			border_color: '#FFFFFF',
			bg_color    : '#FFFFFF',
			title_color : '#000000',
			text_color  : '#000000',
			url_color   : '#000000',
			logo_bgcolor  : '#FFFFFF'
		};
		document.write("<br/><script type='text/javascript' src='http://www.cmking.jp/ads_linkunit/cmking_ad.js'></script>");
	}
	(new Image).src = 'http://log.kayac.com/cl/?rs=i&cm=bm1100010&ln=1';

	var createStage = function(){
		if( typeof(bp_common)=='undefined' ){ throw "needs bp_common framework"; return; }
		b = bp_common;
		//b.hideScrollBars();

		if( !elFloating ){
			elFloating = new bp_elementFactory(
				document.getElementsByTagName("body")[0],
				[ {"tag" : "div",
					"attr":{"id":idFloatingDiv},
					"style":{
						"width"  :"1px",
						"height" :"1px",
						"zIndex" :"2001",
						"display":"block"
					}
                  } ]
            );
            var floating = new SWFObject( gallery_bp_server+swfFloating[swf_index], idFloatingSwf, '100%', '100%', '9', '#000000' );
            floating.addParam('quality','high');
            floating.addParam('wmode','transparent');
            floating.addParam('allowScriptAccess','always');
            floating.addVariable('style',params['style']);
            floating.write( idFloatingDiv );
			gallery_elSwf = navigator.userAgent.match(/MSIE/) ? window[idFloatingSwf] : document[idFloatingSwf];
		}
	};

	var updatePosition = function(){
		aWindowSize = b.getWindowSize();
		aScrollSize = b.getScrollSize();
		aScrollPos	= b.getScrollPosition();
		if( active ){
			elFloating.style.width  = "100%";
			elFloating.style.height = aWindowSize[1]+"px";
			elFloating.style.left   = aScrollPos[0]+"px";
			elFloating.style.top    = aScrollPos[1]+"px";
		}else{
			elFloating.style.width  = "1px";
			elFloating.style.height = "1px";
			elFloating.style.left   = aScrollPos[0]+"px";
			elFloating.style.top    = aScrollPos[1]+"px";
		}
	};

	var showStage = function(){
		b.deleteObstacles();
		updatePosition();
		if( navigator.userAgent.match( "MSIE" ) ){
			document.onmousewheel = Gallerybp.onMouseWheel;
		}else if( navigator.userAgent.match( "Safari" ) ){
			window.onmousewheel = Gallerybp.onMouseWheel;
		}else if(window.opera){
			window.attachEvent("onmousewheel",Gallerybp.onMouseWheel);
		}else if(window.addEventListener){
			window.addEventListener( "DOMMouseScroll", Gallerybp.onMouseWheel, false );
		}
	};

	return {
		timer : null,
		laststyle : null,
		scanindex : 0,
		scantags : [],
		infected : [],
		load : function(){
			createStage();
			updatePosition();
            setTimeout( function() {
                if ( typeof(gallery_elSwf.xi_append)=="function" ) {
                    Gallerybp_gm = new GalleryManager();
                    return;
                }
                setTimeout( arguments.callee, 100 );
            }, 100 );
			b.addListener("DisplayArea","change",updatePosition,false);
			b.addListener( window,      "load",  updatePosition,false);
		},
		show : function(a){
			if( !Gallerybp_gm.initialized ){ return; }
			active = true;
			showStage();
			setTimeout( function(){
				Gallerybp_gm.showImage(a);
			},100);
		},
		end : function(){
			//b.removeListener("DisplayArea","change",updatePosition,false);
			active = false;
			if( navigator.userAgent.match( "MSIE" ) ){
				document.onmousewheel = null;
			}else if( navigator.userAgent.match( "Safari" ) ){
				window.onmousewheel   = null;
			}else if(window.opera){
				window.detachEvent("onmousewheel",Gallerybp.onMouseWheel);
			}else if(window.addEventListener){
				window.removeEventListener( "DOMMouseScroll", Gallerybp.onMouseWheel, false );
			}
			setTimeout( function(){
				updatePosition();
				//elFloating.style.width= '1px';
				//elFloating.style.height='1px';
				b.revivalObstacles();
			},0);
		},
		showThese : function(urls,focusindex){
			var newgalleryid = Gallerybp_gm.Galleries.length;
            setTimeout( function() {
                if ( Gallerybp_gm.initialized ) {
			        active = true;
				    if( shownFromBlogparts ){
				        showStage();
					    setTimeout(function(){
					        gallery_elSwf.xi_showImage( newgalleryid, focusindex );
					    },0);
					    return;
				    }
				    var photoid = 0;
				    urls.bpc_each( function(url){
				        url = b.addDomain(url);
					    gallery_elSwf.xi_append( newgalleryid, photoid, url, "" );
					    photoid++;
				    });
				    shownFromBlogparts = true;
				    Gallerybp.showThese(null,focusindex);
                    return;
                }
                setTimeout( arguments.callee, 100 );
            }, 100 );
		},
		requestPhotos : function(){
			setTimeout( function(){
				if( b==null || typeof(Gallerybp_gm)=="undefined" || !Gallerybp_gm.initialized){
					setTimeout(Gallerybp.requestPhotos,50);
					return;
				}
				var n = 0;
				gallery_sidebarswf = navigator.userAgent.match(/MSIE/) ? window[idSidebarSwf] : document[idSidebarSwf];
				Gallerybp_gm.Galleries.bpc_each( function(g){
					g.imgs.bpc_each( function(i){
						var url = i.parentNode.href  || i.src;
						if( gallery_sidebarswf ){
							gallery_sidebarswf.xi_SidebarAppend( url );
						}
						n++;
					} );
				} );
				if( !n && gallery_sidebarswf ){
					gallery_sidebarswf.xi_showNoPhoto();
				}
			},0 );
		},
		onMouseWheel : function(e){
			var delta;
			if( navigator.userAgent.match( "MSIE" ) ){
				e = window.event;
				delta = e.wheelDelta; e.returnValue = false;
			}else if( navigator.userAgent.match( "Gecko" ) ){
				delta = e.detail * -1; e.preventDefault();
			}else if( window.opera ){
				delta = e.detail * -1; e.preventDefault();
			}else if( navigator.userAgent.match( "Safari" ) ){
				delta = e.wheelDelta; e.returnValue = false;
			}
			delta = ( delta < 0 ) ? -1 : 1;
			gallery_elSwf.xi_zoom(delta);
			if (e.preventDefault) {
				e.preventDefault();
			}
			e.returnValue = false;
		}
	};
}();


var GalleryManager = function(){
	this.initialize();
};
GalleryManager.prototype = {
	b : null,
	initialized: false,
	Galleries : [],
	initialize: function(){
		var slf = this;
		b = bp_common;
		var images = document.body.getElementsByTagName("img");
		var ai = b.asArray( images );
		var re_nodeName = new RegExp(/a/i);
		var re_imgName = new RegExp(/.+(jpg|jpeg|gif|png|bmp)$/i);
		var ai2 = ai.bpc_filter( function(i){
			var p = i.parentNode;
			if( !re_nodeName.test(p.nodeName) ){
				return false;
			}
			var href = p.getAttribute('href');
			if( !href ){
				return false;
			}
			if( re_imgName.test(href) ){
				return true;
			}else{
				return false;
			}
		});
		ai2.bpc_each( function(i){
			var p = slf.getParentDiv(i);
			var e = slf.exists( p );
			var anchor = i.parentNode;
			if( e.length==0 ){
				slf.Galleries.push( new Gallery(i,p) );
			}else{
				var iid = e[0].append( i );
			}
			anchor.onclick=function(){
				Gallerybp.show(this);
				return false;
			};
		});
		setTimeout( function(){
			this.sendToSwf();
		}.bpc_bind(this), 0 );
	},
	sendToSwf : function(){
		Gallerybp_gm.Galleries.bpc_each( function(g,idx){
			g.imgs.bpc_each( function(p,jdx){
				var txt = p.parentNode.title || p.title || p.alt;
				var url = p.parentNode.href  || p.src;
				url = b.addDomain(url);
				gallery_elSwf.xi_append(idx,jdx,url,txt);
			} );
		} );
		Gallerybp_gm.initialized = true;
	},
	showImage : function(a){
		var loc = this.getGallery(a);
		if( loc==null ){
			return false;
		}
		if( gallery_elSwf && gallery_elSwf.xi_showImage && Gallerybp_gm.initialized ){
			gallery_elSwf.xi_showImage( loc[0], loc[1] );
		}else{
			return false;
		}
	},
	getGallery : function( anchor ){
		var len = this.Galleries.length;
		for( var i=0; i<len; i++ ){
			var incl = this.Galleries[i].includes( anchor );
			if( incl != null ){
				return [i,incl];
			}
		}
		return null;
	},
	getParentDiv : function( img ){
		var p = img;
		var n = p.nodeName.toLowerCase();
		while( n != "body" && n != "div" ){
			p = p.parentNode;
			n = p.nodeName.toLowerCase();
		}
		return p;
	},
	exists : function(div){
		return this.Galleries.bpc_filter( function(g){
			if( g.div == div ){
				return true;
			}else{
				return false;
			}
		});
	}
};
var Gallery = function(img,div){
	this.initialize(img,div);
};
Gallery.prototype = {
	imgs: null,
	div: null,
	initialize: function(img,div){
		this.imgs = new Array();
		this.imgs.push( img );
		this.div = div;
	},
	// return index of added img
	append: function(img){
		this.imgs.push( img );
		return (this.imgs.length-1);
	},
	includes : function( anchor ){
		var len = this.imgs.length;
		for( var i=0; i<len; i++ ){
			if( this.imgs[i].parentNode == anchor ){
				return i;
			}
		}
		return null;
	}
};

