var Link;
var imgSize = 160;
var fileName = 'puzzle.js';
var fileNameLen = fileName.length;
var imgParam = new Object();
var queryPrm = 'painting';
var maxResults = 10;
var ImgUrl = '';
var baseColor = 'white';

function main() {
    // $Id: f9puzzle.js,v 1.7 2008/12/09 04:26:53 Exp $
    //Copyright (C) Fenrir Inc. All Rights Reserved

    // ini start
    var initCounter = 1280;
    var numPict = 3; // 3 x 3
    var framePadding = {top:46, left:12, right:12, bottom:48, middle:0}; // 148x218
    var threshold = {sizeMin:160, sizeMax:640, numMin:2, numMax:10};
    // var areaSize = threshold.sizeMin;
    var areaSize = imgSize;

    var linkUrl = '';
    var urlPref = 'http://www.spread-grani.com/blogparts/';
if( ImgUrl == '' ){
	ImgUrl = urlPref + 'img/' + baseColor + '/text/error.png';
}
    var imgUrl = ImgUrl;

    var iconSize = {
        start:{x:8, y:37},
        reset:{x:7, y:27},
        hint:{x:21, y:7},
        getme:{x:7, y:62},
        getpnir:{x:9, y:8},
        powered:{x:68, y:13},
        logo:{x:39, y:11},
        time:{x:8, y:8},
        move:{x:8, y:8},
        num:{x:7, y:9},
        colon:{x:7, y:9},
        clear:{x:120, y:86}
    };
    var urls = {
        getMe:{
            ja:'http://www.spread-grani.com/',
            us:'http://en.spread-grani.com/'

            // ja:'http://www.fenrir.co.jp/labs/web/logica/',
            // us:'http://www.fenrir-inc.com/us/sleipnir/laboratory/web/logica/'
        },
        getSleipnir:{
            ja:'http://twitter.com/home?status=RT%20%40SPGRA%20%5BSPGRA%209P%5D%20%E5%A5%BD%E3%81%8D%E3%81%AA%E5%86%99%E7%9C%9F%E3%82%84%E7%94%BB%E5%83%8F%E3%81%A7%209%20%E3%83%91%E3%82%BA%E3%83%AB%E3%82%92%E4%BD%9C%E3%81%A3%E3%81%A6%E9%81%8A%E3%81%B9%E3%82%8B%E3%83%96%E3%83%AD%E3%82%B0%E3%83%91%E3%83%BC%E3%83%84%20http%3A%2F%2Fbit.ly%2F7MFjPn',
            us:'http://en.spread-grani.com/'

            // ja:'http://www.fenrir.co.jp/sleipnir/',
            // us:'http://www.fenrir-inc.com/us/sleipnir/'
        },
        goFenrir:{
            ja:'http://www.fenrir.co.jp/',
            us:'http://www.fenrir-inc.com/'
        }
    };
    // ini end

    /*@cc_on _d=document;eval('var document=_d')@*/ // for ie

    // create obj_id prefix string
    var idPrefix = '';
    for (var i = 0; i < 32; i++)
        idPrefix += String.fromCharCode( Math.floor(Math.random()*25) +97 );

    // set movable position
    var movablePos = [];
    for ( var i = 0; i < numPict * numPict; i++ ) {
        var array = [];
        if ( i - numPict  >= 0 ) // upper
            array.push( i - numPict );
        if ( i % numPict > 0 ) // left
            array.push( i - 1 );
        if ( i % numPict < numPict -1 ) // right
            array.push( i + 1);
        if ( i + numPict < numPict * numPict ) // lower
            array.push( i + numPict );
        movablePos.push( array );
    }
    var movablePos_len = movablePos.length;

    // set initial image position
    var imgPos = [];
    for ( var i = 0; i < movablePos_len; i++ ) {
        if ( i == movablePos_len -1 )
            imgPos.push('');
        else
            imgPos.push(i+'');
    }

    var isCorrect = 1;
    var logicaCounter = 0;
    var logicaTimer = 0;
    var logicaCounterMax = 99999999;  // move counter limit
    var logicaTimerMax = 359999;      // time counter limit (s) // 99:59:59

    function o(id) { return document.getElementById(id); }
    // get language
    function getBrowserLang() {
        var lang = '';
        if ( document.all ) {
            if ( window.navigator.userLanguage.match(/ja/) )
                lang = 'ja';
        }
        else if ( document.layers || document.getElementById ) {
            if ( window.navigator.language.match(/ja/) )
                lang = 'ja';
        }
        return lang;
    }
    // set opacity
    function _setOp(obj,op) {
        if ( document.all )
            obj.style.filter='alpha(opacity='+(op*100)+')';
        else {
            obj.style.MozOpacity = op;   // Moziila, Firefox
            obj.style.opacity = op;      // Safari >=1.2 
            obj.style.KHTMLOpacity = op; // Safari < 1.2
        }
    }
    // support png (alpha channel) on IE5.5/6.x
    function _transPngForIE(obj,scale) {
        if ( document.all && navigator.userAgent.match(/MSIE (5\.5|6\.)/) ) {
            var bgimg = obj.style.backgroundImage;
            var filtername = 'DXImageTransform.Microsoft.AlphaImageLoader';
            if ( bgimg.match(/^url\([\"']?(.*\.png)["']?\)$/i)) {
                imgurl = RegExp.$1;
                obj.style.backgroundImage = 'none';

                if ( scale == null )
                    scale = 'crop';

                obj.style.filter = 'progid:' + filtername + '(src="' + imgurl + '", sizingMethod="'+scale+'")';
                obj.runtimeStyle.behavior = 'none'; // I'm not browser crasher.
            }
        }
    }
    // create tile image obj and return obj
    function _createImgElm(num, border) {
        var len = Math.floor( areaSize / numPict );
        var shiftx = (num % numPict) * len * -1;
        var shifty = Math.floor( num / numPict ) * len * -1;

        var div = document.createElement('div');
        with (div.style) {
            position = 'relative';
            margin = 0;
            padding = 0;
            textAlign = 'left';
        }

        var imgPadding = 1;
        var imgBorder = 1;
        if ( border == 0 )
            imgPadding = 0;
        if ( border != null )
            imgBorder = border;

        var totalPadding = imgBorder + imgPadding;
        var vlen = len - totalPadding * 2

        // create image
        var img = document.createElement('div');
        with (img.style) {
            position = 'absolute';
            margin = 0;
            padding = 0;
            top = totalPadding + 'px';
            left = totalPadding + 'px';
            width = vlen + 'px';
            height = vlen + 'px';
            cursor = 'pointer';
            // backgroundImage = 'url("' + imgUrl + '")';
            // backgroundPosition = (shiftx - totalPadding) + 'px ' + (shifty - totalPadding) + 'px';
            overflow = 'hidden';
        }
        div.appendChild(img);

	// background -> image by nishi
	var fImg = document.createElement('img');
	fImg.src = imgUrl;
	fImg.onerror = function(){
		if(fImg.src == urlPref + 'img/' + baseColor + '/text/error.png'){
			return;
		}
		ImgUrl = imgUrl = fImg.src = urlPref + 'img/' + baseColor + '/text/error.png';
	}

	fImg.style.position = 'absolute';
	fImg.style.left = (shiftx - totalPadding) + 'px ';
	fImg.style.top = (shifty - totalPadding) + 'px ';

	fImg.style.width = imgSize + 'px';
	fImg.style.height = imgSize + 'px';


	// fImg.style.zIndex = 0;

        img.appendChild(fImg);

        if ( imgBorder > 0 ) { // border
            var lineImg = [];
            var lineCover = [];  // for shadow
            // create border (common property)
            for ( var i = 0; i < 4; i++ ) {
                var img = document.createElement('div');
                var cvr = document.createElement('div');
                var is = img.style;
                var cs = cvr.style;
                is.position = 'absolute';
                is.margin   = 0;
                is.padding  = 0;
                // is.backgroundImage = 'url("' + imgUrl + '")';
                is.overflow = 'hidden'; // for ie
		// is.zindex = 5

                cs.position = 'absolute';
                cs.margin   = 0;
                cs.padding  = 0;
                cs.overflow = 'hidden'; // for ie
		cs.zindex = 5

                // lineImg.push(img);
                lineCover.push(cvr);
                div.appendChild(img);
                div.appendChild(cvr);

		var fImg2 = document.createElement('img');
		fImg2.src = imgUrl;

		fImg2.style.width = imgSize + 'px';
		fImg2.style.height = imgSize + 'px';

		fImg2.style.position = 'absolute';

		lineImg.push(fImg2);

		img.appendChild(fImg2);
            }
            this._cBorder = function(num, shiftT, shiftL, w, h) {
                var is = lineImg[num].style;
                is.top    = shiftT + 'px';
                is.left   = shiftL + 'px';
                is.width  = w + 'px';
                is.height = h + 'px';
                var cs = lineCover[num].style;
                cs.top    = shiftT + 'px';
                cs.left   = shiftL + 'px';
                cs.width  = w + 'px';
                cs.height = h + 'px';
            }

            //top border
            this._cBorder(0, imgPadding, totalPadding, vlen, imgBorder);
            lineImg[0].style.left = (shiftx - totalPadding) + 'px ';
            lineImg[0].style.top = (shifty - totalPadding) + 'px ';

            // lineImg[0].style.backgroundPosition = (shiftx - totalPadding) + 'px ' + (shifty - imgPadding) + 'px';
            lineCover[0].style.backgroundColor = '#fff';
            _setOp(lineCover[0], 0.3);

            //right border
            this._cBorder(1, totalPadding, len - totalPadding, imgBorder, vlen);
            lineImg[1].style.left = (shiftx - len + totalPadding) + 'px ';
            lineImg[1].style.top = (shifty - totalPadding) + 'px ';

            // lineImg[1].style.backgroundPosition = (shiftx - len + totalPadding) + 'px ' + (shifty - totalPadding) + 'px';
            lineCover[1].style.backgroundColor = '#fff';
            _setOp(lineCover[1], 0.15);

            //bottom border
            this._cBorder(2, len - totalPadding, totalPadding, vlen, imgBorder);
            lineImg[2].style.left = (shiftx - totalPadding) + 'px ';
            lineImg[2].style.top = (shifty - len + totalPadding) + 'px ';

            // lineImg[2].style.backgroundPosition = (shiftx - totalPadding) + 'px ' + (shifty - len + totalPadding) + 'px';
            lineCover[2].style.backgroundColor = '#000';
            _setOp(lineCover[2], 0.3);

            //left border
            this._cBorder(3, totalPadding, imgPadding, imgBorder, vlen);
            lineImg[3].style.left = (shiftx - imgPadding) + 'px ';
            lineImg[3].style.top = (shifty - totalPadding) + 'px ';

            // lineImg[3].style.backgroundPosition = (shiftx - imgPadding) + 'px ' + (shifty - totalPadding) + 'px';
            lineCover[3].style.backgroundColor = '#fff';
            _setOp(lineCover[3], 0.15);
        }
        return div;
    }
    function _getBlankPos() {
        var blankPos = 0;
        for ( var i = 0; i < movablePos_len; i++ ) {
            if ( imgPos[i] == '' ) {
                blankPos = i;
                break;
            }
        }
        return blankPos;
    }
    // create and view counter obj ( time )
    function _timeCounter(idSuf,shiftT,shiftL) {
	var congFlag = false;
        if ( ! idSuf ) idSuf = '_time';
        if ( ! shiftT ) {
		shiftT = 0;
	}
	else {
		congFlag = true;
	}
        if ( ! shiftL ) shiftL = 12 + 4; // icon size + padding
        var baseId = idPrefix + idSuf;
        var str = logicaTimer + '';
        var max = logicaTimerMax + '';

        var hour = Math.floor(logicaTimer / 3600);
        var min  = Math.floor( (logicaTimer - hour * 3600) / 60 );
        var sec  = logicaTimer - hour * 3600 - min * 60;
        hour = hour < 10 ? '0' + hour : hour;
        min = min < 10 ? '0' + min : min;
        sec = sec < 10 ? '0' + sec : sec;
        var now = hour + ':' + min + ':' + sec;

        for ( var i = 0, nlen = now.length; i < nlen; i++ ) {
            var t = now.charAt(i);
            var id = baseId + '_t' + i;
            if ( o(id) )
                o(baseId).removeChild( o(id) );

            var obj = document.createElement('div');
            obj.id = id;
            var name = t;
            var w = iconSize.num.x;
            if ( i == 2 || i == 5 ) {
                name = 'colon';
                w = iconSize.colon.x;
            }

            with ( obj.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                top = shiftT + 'px';
                // left = (shiftL + i * iconSize.num.x - 4 * Math.floor( i / 3)) + 'px';
		left = ( shiftL + ( i * 7 ) ) + 'px';
                width = w + 'px';
                height = iconSize.num.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/time/' + name + '.png")';
                backgroundRepeat = 'no-repeat';
            }

            if( congFlag ){
	        obj.style.backgroundImage = 'url("' + urlPref + 'img/black/time/' + name + '.png")';
	    }

            o(baseId).appendChild(obj);
            _transPngForIE(obj);
        }
    }
    // create and view counter obj ( move )
    function _moveCounter(idSuf,shiftT,shiftL) {
	var congFlag = false;

        if ( ! idSuf ) idSuf = '_move';
        if ( ! shiftT ) {
		shiftT = 0;
	}
	else {
		congFlag = true;
	}

        // if ( ! shiftL ) shiftL = 12 + 4;
        if ( ! shiftL ) shiftL = 5;
        var baseId = idPrefix + idSuf;
        var str = logicaCounter + '';
        var max = logicaCounterMax + '';

        for ( var i = 0, mlen = max.length, slen = str.length; i < mlen; i++ ) {
            var id = baseId + '_m' + i;
            if ( o(id) ){
                o(baseId).removeChild( o(id) );
	    }

            // if ( slen > i ) {

	    if ( 4 > i ) {
                var num = str.charAt(slen - i -1);
		if( num == '' ) {
			num = "0";
		}

                var obj = document.createElement('div');
                obj.id = id;
                with ( obj.style ) {
                    position = 'absolute';
                    margin = 0;
                    padding = 0;
                    top = shiftT + 'px';
                    left = (shiftL + iconSize.num.x * ( 6 - i ) - 2) + 'px';
                    width = iconSize.num.x + 'px';
                    height = iconSize.num.y + 'px';
                    backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/time/' + num + '.png")';
                    backgroundRepeat = 'no-repeat';
                }
		if( congFlag ){
			obj.style.backgroundImage = 'url("' + urlPref + 'img/black/time/' + num + '.png")';
			obj.style.left = (shiftL + iconSize.num.x * ( 6 - i ) - 2) + 9 + 'px';
		}

                o(baseId).appendChild(obj);
                _transPngForIE(obj);
            }
        }
    }

    // game start !
    function gameStart() {
        initializePuzzle();

        // toggle button
        o(idPrefix + '_start_button').style.visibility='hidden';
        o(idPrefix + '_reset_button').style.visibility='visible';

        // Initialize Position
        for ( var i = 0; i < initCounter; i++ ) {
            var blankPos = _getBlankPos();
            var rand = Math.floor( Math.random() * movablePos[blankPos].length );

            var newPos = movablePos[blankPos][rand];
            var tmp = imgPos[newPos];
            imgPos[newPos] = '';
            imgPos[blankPos] = tmp;
        }

        // Set images
        for ( var i = 0; i < movablePos_len; i++ ) {
            var id = idPrefix + '_pict' + i;
            if ( o(id).firstChild )
                o(id).removeChild( o(id).firstChild );
            if ( imgPos[i] ) {
                img = _createImgElm(imgPos[i]);
                o(id).appendChild(img);
            }
        }

        // Game Start
        isCorrect=0;
    }

    function moveImage(targetImgNum) {
        if ( ! isCorrect ) {
            // Get blank position
            var blankPos = _getBlankPos();

            // Move image
            for ( var i = 0, mlen = movablePos[targetImgNum].length; i < mlen; i++ ) {
                if ( movablePos[targetImgNum][i] == blankPos ) {  // if movable
                    var tmp = imgPos[targetImgNum]; // deposit img num;
                    var newPosId = idPrefix + '_pict' + blankPos;
                    var oldPosId = idPrefix + '_pict' + targetImgNum;

                    img = _createImgElm(tmp);
                    o(newPosId).appendChild(img);

                    o(oldPosId).removeChild( o(oldPosId).firstChild );

                    imgPos[targetImgNum] = '';
                    imgPos[blankPos] = tmp;

                    if ( logicaCounter < logicaCounterMax )
                        logicaCounter++;

                    _moveCounter();
                }
            }

            // is correct ?
            var chk = 0;
            for ( var i = 0; i < movablePos_len; i++ ) {
                if( imgPos[i] == i)
                    chk++;
            }
            // congratulations !
            if ( chk == movablePos_len -1 ) {
                isCorrect = 1;
                o( idPrefix + '_pict' + (movablePos_len -1) ).appendChild( _createImgElm(movablePos_len -1) );

                // change mouse-cursor style and image-border style
                for ( var i = 0; i < movablePos_len; i++ ) {
                    var t = o(idPrefix + '_pict' + i);
                    var img = _createImgElm(i,0);
                    if ( t.firstChild )
                        t.removeChild( t.firstChild );
                    img.style.cursor = 'default';
                    t.appendChild(img);
                }

                // view congratulations message
                o(idPrefix+'_congratulations').style.visibility= 'visible'; // shadow
                _moveCounter('_congratulations_img', 66,54);
                _timeCounter('_congratulations_img', 56,54);
                o(idPrefix+'_congratulations_img').style.visibility= 'visible';

                // toggle button
                o(idPrefix+'_start_button').style.visibility = 'visible';
                o(idPrefix+'_reset_button').style.visibility = 'hidden';
            }
        }
    }
    this.countUp = function() {
        if ( ! isCorrect && logicaTimer < logicaTimerMax ) {
            logicaTimer++;
            _timeCounter();
        }
    }
    function initializePuzzle() {
        isCorrect = 1;
        logicaCounter = 0;
        logicaTimer = 0;

        // var realSize = Math.floor( areaSize / numPict ) * numPict;
	var realSize = imgSize;

        // puzzle area
        var baseName = idPrefix + '_f9puzzle_base_area';
        if ( ! o(baseName) ){
		// document.write('<div id="'+baseName+'" style="position:relative;margin:0;padding:0;text-align:left;"></div>');

		var base_div = document.createElement('div');
		base_div.id = baseName;
		with ( base_div.style ) {
			position = 'relative';
			margin = 0;
			padding = 0;
			textAlign = 'left';
			width = '200px';
			height = '200px';
		};
		document.getElementById("spgra_area").appendChild(base_div);
	}

        // for href
        var lang = getBrowserLang();
        if ( lang != 'ja' )
            lang = 'us';

        // picture area
        if ( ! o(idPrefix+'_picture') ) {
            var div = document.createElement('div');
            div.id = idPrefix+'_picture';
            with ( div.style ) {
                position = 'absolute';
                // top = framePadding.top + 'px';
                // left = framePadding.left + 'px';
		top = '19px';
		left = '19px';
                margin = 0;
                padding = 0;
		border = 'solid 1px rgb(255,0,255)';
            };
            o(baseName).appendChild(div);
        }

        // image area
        var tbl = document.createElement('div');
        with ( tbl.style ) {
            position = 'relative';
            margin = 0;
            padding = 0;
            backgroundColor = '#000';
            width = realSize + 'px';
            height= realSize + 'px';
        };
        for ( var i = 0; i < movablePos_len; i++ ) {
            var td = document.createElement('div');
            td.id = idPrefix + '_pict' + i;
            var img = _createImgElm(i);
            img.style.cursor = 'default';
            td.appendChild( img );
            td.onclick = (function(num) { return function() {
                if ( ! isCorrect )
                    moveImage(num);
                else if ( o(idPrefix + '_congratulations').style.visibility == 'visible' )
                    initializePuzzle();
                else
                    gameStart();
                return false;
            }})(i);
            td.onmouseout = function() {return false;};
            td.onmouseup = function() {return false;};
            var w = Math.floor(areaSize / numPict);
            with ( td.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                top = (Math.floor( i / numPict ) * w) + 'px';
                left = (( i % numPict ) * w) + 'px';
                width = w + 'px';
                height = w + 'px';
            };
            tbl.appendChild(td);
        }

        if ( o(idPrefix+'_picture').firstChild )
            o(idPrefix+'_picture').removeChild( o(idPrefix+'_picture').firstChild );
        o(idPrefix+'_picture').appendChild(tbl);

        // start button
        if ( ! o(idPrefix+'_start_button') ) {
            var div = document.createElement('div');
            div.id = idPrefix+'_start_button';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = (framePadding.top - iconSize.start.y - 4) + 'px';
                // left = (framePadding.left + realSize - iconSize.start.x + 3) + 'px';
		top = '81px';
		left = '184px'
                width = iconSize.start.x + 'px';
                height = iconSize.start.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/'  + baseColor +  '/button/shufflebtn_n.png")';
                backgroundRepeat = 'no-repeat';
                cursor = 'pointer';
            }
            // mouse event
            div.title = 'Shuffle';
            div.onmousedown = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor +  '/button/shufflebtn_d.png")';_transPngForIE(this); return false;};
            div.onmouseup = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/shufflebtn_n.png")';_transPngForIE(this); return false;};
            div.onmouseout = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/shufflebtn_n.png")';_transPngForIE(this); return false;};
            div.onclick = function() { gameStart(); return false; };

            o(baseName).appendChild(div);
            _transPngForIE(div);
        }

        // reset button
        if ( ! o(idPrefix+'_reset_button') ) {
            var div = document.createElement('div');
            div.id = idPrefix+'_reset_button';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = (framePadding.top - iconSize.reset.y - 4) + 'px';
                // left = (framePadding.left + realSize - iconSize.reset.x + 3) + 'px';
		top = '86px';
		left = '184px'
                width = iconSize.reset.x + 'px';
                height = iconSize.reset.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/resetbtn_n.png")';
                backgroundRepeat = 'no-repeat';
                cursor = 'pointer';
            }
            // mouse event
            div.title = 'Reset';
            div.onmousedown = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/resetbtn_d.png")';_transPngForIE(this); return false;};
            div.onmouseup = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/resetbtn_n.png")';_transPngForIE(this); return false;};
            div.onmouseout = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/resetbtn_n.png")';_transPngForIE(this); return false;};
            div.onclick = function() { initializePuzzle(); return false;};

            o(baseName).appendChild(div);
            _transPngForIE(div);
        }
        o(idPrefix+'_start_button').style.visibility = 'visible';
        o(idPrefix+'_reset_button').style.visibility = 'hidden';

        // get logica
        if ( ! o(idPrefix+'_get_logica') ) {
            var div = document.createElement('div');
            div.id = idPrefix+'_get_logica';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = (framePadding.top + realSize + 10) + 'px';
                // left = (framePadding.left + realSize + framePadding.right - iconSize.getme.x - iconSize.getpnir.x)/2 + 'px';

		top = '115px';
		left = '10px';
                width = iconSize.getme.x + 'px';
                height = iconSize.getme.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/getme_n.png")';
                backgroundRepeat = 'no-repeat';
                cursor = 'pointer';
            };
            // mouse event
            div.onmousedown = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/getme_d.png")';_transPngForIE(this); return false;};
            div.onmouseup = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/getme_n.png")';_transPngForIE(this); return false;};
            div.onmouseout = function() { this.style.backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/getme_n.png")';_transPngForIE(this); return false;};
            div.onclick = function() { window.open(urls.getMe['ja']); return false; }

            o(baseName).appendChild(div);
            _transPngForIE(div);
        }

        // get sleipnir
        if ( ! o(idPrefix+'_get_sleipnir') ) {
            var div = document.createElement('div');
            div.id = idPrefix+'_get_sleipnir';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                //top = (framePadding.top + realSize + 4) + 'px';
                //left = (framePadding.left + realSize - iconSize.getpnir.x + 4) + 'px';
                //left = ((framePadding.left + realSize + framePadding.right - iconSize.getme.x - iconSize.getpnir.x)/2 + iconSize.getme.x) + 'px';
                top = '100px';
                left = '9px';

		width = iconSize.getpnir.x + 'px';
                height = iconSize.getpnir.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/tw.png")';
                backgroundRepeat = 'no-repeat';
                cursor = 'pointer';
            };
            // mouse event
            div.onclick = function() { window.open(urls.getSleipnir['ja']); return false;};
            o(baseName).appendChild(div);
            _transPngForIE(div);
        }

        // time counter
        if ( ! o(idPrefix + '_time') ) {
            var div = document.createElement('div');
            div.id = idPrefix + '_time';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = o(idPrefix + '_start_button').style.top; // same as start button
                // left = framePadding.left + 'px';
		top = '9px';
		left = '108px';
            }
            o(baseName).appendChild(div);
        }
        _timeCounter();
        // move counter
        if ( ! o(idPrefix + '_move') ) {
            var div = document.createElement('div');
            div.id = idPrefix + '_move';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = (framePadding.top - iconSize.start.y - 4 + 12) + 'px'; // start button based
                // left = framePadding.left + 'px';
		top = '9px';
		left = '0px';
                width = ( iconSize.time.x + 4 + iconSize.num.x * 6 + iconSize.colon.x * 2 ) + 'px';
            }

	    o(baseName).appendChild(div);
        }
        _moveCounter();

        // cograturations message area
        if ( o(idPrefix+'_congratulations') ) {
            o(idPrefix+'_congratulations').style.visibility= 'hidden';
            o(idPrefix+'_congratulations_img').style.visibility= 'hidden';
        }
        else {
            // shadow
            var div = document.createElement('div');
            div.id = idPrefix+'_congratulations';
            with ( div.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = framePadding.top + 'px';
                // left = framePadding.left + 'px';
		top = "20px";
		left = "20px";
                width = realSize + 'px';
                height= realSize + 'px';
                cursor = 'pointer';
                backgroundColor = '#000';
                visibility = 'hidden';
            };
            o(baseName).appendChild(div);
            _setOp(div, 0.5);
            div.onclick = function() {initializePuzzle(); return false;};
            div.onmouseout = function() {return false;};
            div.onmouseup = function() {return false;};
            // background
            var img = document.createElement('div');
            img.id = div.id + '_img';
            with ( img.style ) {
                position = 'absolute';
                margin = 0;
                padding = 0;
                // top = (framePadding.top + Math.floor((realSize - iconSize.clear.y) / 2)) + 'px';
                // left = (framePadding.left +  Math.floor((realSize - iconSize.clear.x) / 2)) + 'px';
		top = "57px";
		left = "40px";
                width = iconSize.clear.x + 'px';
                height = iconSize.clear.y + 'px';
                backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/text/clear.png")';
                backgroundRepeat = 'no-repeat';
                cursor = 'pointer';
                visibility = 'hidden';
            };
            o(baseName).appendChild(img);
            _transPngForIE(img);
            img.onclick = function() {initializePuzzle(); return false;};
            img.onmouseout = function() {return false;};
            img.onmouseup = function() {return false;};
        }

        // hint button
        if ( o(idPrefix + '_hint') )
            o(baseName).removeChild( o(idPrefix + '_hint') );
        var hn = document.createElement('div');
        hn.id = idPrefix+'_hint';
        with ( hn.style ) {
            position = 'absolute';
            margin = 0;
            padding = 0;
            // top = (framePadding.top - iconSize.hint.y - 4) + 'px';
            // left = (framePadding.left + realSize - iconSize.hint.x - iconSize.start.x + 2) + 'px';
	    top = '183px';
	    left = '91px'

            width = iconSize.hint.x + 'px';
            height = iconSize.hint.y + 'px';
            backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/hintbtn_n.png")';
            backgroundRepeat = 'no-repeat';
            cursor = 'pointer';
        }
        hn.title = 'Hint';
        hn.onmousedown = function() {o(idPrefix+'_hint_area').style.visibility='visible';return false;};
        hn.onmouseup = function() {o(idPrefix+'_hint_area').style.visibility='hidden';return false;};
        o(baseName).appendChild(hn);
        _transPngForIE(hn);

        // hint area
        if ( o(idPrefix+'_hint_area') )
            o(baseName).removeChild( o(idPrefix + '_hint_area') );
        var h = document.createElement('div');
        h.id = idPrefix+'_hint_area';
        with ( h.style ) {
            position = 'absolute';
            // top = (framePadding.top - iconSize.hint.y - 4) + 'px';
            // left = framePadding.left + 'px';
	    top = "20px";
	    left = "20px";
            margin = 0;
            padding = 0;
            width = realSize + 'px';
            // height = (realSize + iconSize.hint.y + 4) + 'px';
	    height = realSize + 'px';
            visibility = 'hidden';
        };
        o(baseName).appendChild(h);

        // hint picture
        if ( o(idPrefix+'_hint_picture') )
            h.removeChild( o(idPrefix + '_hint_picture') );
        var div = document.createElement('div');
        div.id = idPrefix+'_hint_picture';
        with ( div.style ) {
            position = 'absolute';
            // top = (iconSize.hint.y + 4) + 'px';
	    top = '0px';
            left = '0px';
            margin = 0;
            padding = 0;
            width = realSize + 'px';
            height = realSize + 'px';
            // backgroundImage = 'url("' + imgUrl + '")';
        };
        h.appendChild(div);

	var fImg = document.createElement('img');

	fImg.src = imgUrl;
	fImg.onerror = function(){
		if(fImg.src == urlPref + 'img/' + baseColor + '/text/error.png'){
			return;
		}
		ImgUrl = imgUrl = fImg.src = urlPref + 'img/' + baseColor + '/text/error.png';
	}

	fImg.style.position = 'absolute';
	fImg.style.width = imgSize + 'px';
	fImg.style.height = imgSize + 'px';

	div.appendChild(fImg);

        // hint button (depress)
        if ( o(idPrefix + '_hint_depress' ) )
            h.removeChild( o(idPrefix + '_hint_depress') );
        var hd = document.createElement('div');
        hd.id = idPrefix+'_hint_depress';
        with ( hd.style ) {
            position = 'absolute';
            margin = 0;
            padding = 0;
            // top = '0px';
            // left = (realSize - iconSize.hint.x - iconSize.start.x + 2) + 'px';
	    top = '163px';
	    left = '71px'
            width = iconSize.hint.x + 'px';
            height = iconSize.hint.y + 'px';
            backgroundImage = 'url("' + urlPref + 'img/' + baseColor + '/button/hintbtn_d.png")';
            backgroundRepeat = 'no-repeat';
            cursor = 'pointer';
        }
        hd.onmouseup = function() {o(idPrefix+'_hint_area').style.visibility='hidden';return false;};
        hd.onmouseout = function() {o(idPrefix+'_hint_area').style.visibility='hidden';return false;};
        h.appendChild(hd);
        _transPngForIE(hd);
    }

    initializePuzzle();
    setInterval(this.countUp, 1000);
}


function jsonCallbackApi(data){

	if( data.feed.openSearch$totalResults.$t > 1 ){

		var randnum = Math.floor( Math.random() * data.feed.entry.length );

	        ImgUrl = data.feed.entry[randnum].media$group.media$thumbnail[0].url;

		var imgLinkPoint = ImgUrl.lastIndexOf('/');
		var imgLinkTmp = ImgUrl.substring(0,imgLinkPoint);
		imgLinkPoint = imgLinkTmp.lastIndexOf('/');
		Link = imgLinkTmp.substring(0,imgLinkPoint + 1);
	}

	main();
}

function obj2query ( obj ) {
    var list = [];
    for( var key in obj ) {
        var k = encodeURIComponent(key);
        var v = encodeURIComponent(obj[key]);
        list[list.length] = k+'='+v;
    }
    var query = list.join( '&' );
    return query;
}


var scripts = document.getElementsByTagName('script');
var sLen = scripts.length;
var i;

for(i = 0; i < sLen; i++){
	if ( scripts[i].src && scripts[i].src.match(/puzzle\.js\?(.*)$/) ) {
		var paramPnt = scripts[i].src.indexOf(fileName);
		var paramData = scripts[i].src.substring(paramPnt + fileName.length + 1, scripts[i].src.length);

		while(1) {
			paramPnt = paramData.indexOf('&');
			var paramDataTmp;

			if( -1 != paramPnt ) {
				paramDataTmp = paramData.substring(0,paramPnt);
				if( paramDataTmp.match(/q=*/) ){
					queryPrm = paramDataTmp.substring(2, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/num=*/) ){
					maxResults = paramDataTmp.substring(4, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/img=*/) ){
					ImgUrl = paramDataTmp.substring(4, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/color=*/) ){
					baseColor = paramDataTmp.substring(6, paramDataTmp.length);
				}

				paramData = paramData.substring(paramPnt + 1, paramData.length);
			}
			else {
				paramDataTmp = paramData;
				if( paramDataTmp.match(/q=*/) ){
					queryPrm = paramDataTmp.substring(2, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/num=*/) ){
					maxResults = paramDataTmp.substring(4, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/img=*/) ){
					ImgUrl = paramDataTmp.substring(4, paramDataTmp.length);
				}
				else if( paramDataTmp.match(/color=*/) ){
					baseColor = paramDataTmp.substring(6, paramDataTmp.length);
				}

				break;
			}
		}
	}
}


if(ImgUrl != ''){
	Link = ImgUrl;
	main();
}
else {
	imgParam.kind = 'photo';
	// imgParam.tag = 'painting';
	imgParam.thumbsize = '160';
	imgParam.crop = '1';
	imgParam.alt = 'json-in-script';
	imgParam.callback = 'jsonCallbackApi';

	var reqUrl;
	reqUrl = 'http://picasaweb.google.com/data/feed/api/all?' + 'max-results=' + maxResults + '&q=' + queryPrm + '&' + obj2query( imgParam );
	// alert(reqUrl);
	// reqUrl = encodeURI(reqUrl);

	var s = document.createElement('script');

	s.setAttribute('type', 'text/javascript');
	s.setAttribute('charset', 'UTF-8');
	s.setAttribute('src', reqUrl);

	document.getElementById("spgra_area").appendChild(s);
}
